DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on • Edited on

1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →