DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on • Edited on

SPREAD VS REST OPERATORS

Image description

Spread Operator

Arrays

Imagine you have two lists of friends and you want to combine them into one list.

const schoolFriends = ['Ali', 'Bilol', 'Umar'];
const workFriends = ['Ubayda', 'Hamza', 'Abdulloh'];
const allFriends = [...schoolFriends, ...workFriends]

console.log(allFriends);
Enter fullscreen mode Exit fullscreen mode

Objects

Suppose you have two objects representing your personal and work contact information, and you want to combine them into one contact object.

const personalInfo = {
    name: 'Khojiakbar',
    phone: '90-024-10-98',
}
const workInfo = {
    email: 'hojiakbar7796@mail.ru',
    phone: '010-8210-4488',
}
const combinedInfo = {
    ...personalInfo,
    ...workInfo,
}
console.log(combinedInfo);
Enter fullscreen mode Exit fullscreen mode

Rest Operator

Functions

You are organising a party and want to create a function that takes an indefinite number of guest names and prints them.

function inviteGuests(host, ...guests) {
    console.log(`Host: ${host}`);
    console.log(`Guests: ${guests.join(', ')}`);
}

inviteGuests('Khojiakbar', 'Umar', 'Uthman', 'Bilal');
Enter fullscreen mode Exit fullscreen mode

Arrays

You have a list of tasks for the day and want to separate the first task from the rest.


const firstTask = ['Wake up'];
const remainingTasks = ['Brush your teeth', 'Wash your face', 'Go to work']
console.log(`First task: ${firstTask}`);
console.log(`Remaining tasks: ${remainingTasks.join(', ')}`);
Enter fullscreen mode Exit fullscreen mode

Objects

You have a user profile object and you want to separate the username from the rest of the profile details.

const userProfile = {
    username: 'Khojiakbar',
    age: 26,
    job: 'programmer',
    city: 'Tashkent region',
}

const {username, ...otherDetails} = userProfile

console.log(`Username: ${username}`);
console.log(`Profile Details:`, otherDetails);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)