What is object destructuring and spread operator in JavaScript?

Object destructuring

Object destructuring is a feature in JavaScript which allows us to assign values from arrays and properties from objects to distinct variables. This is also referred to as destructuring assignment.

Examples

Swapping two numbers

let x = 5y = 7;

[xy] = [yx];

console.log(xy); // 7 5

Taking out values from an array and assigning them to variables

let array = [12345678];

const [, a, , , bc] = array;

console.log(abc); // 2 5 6

Assigning remaining values to a variable

let array = [123456789];

const [x, ...y] = array;

console.log(x);

console.log(y);

// 1

// [

//   2, 3, 4, 5,

//   6, 7, 8, 9

// ]

Taking out properties from an object and assigning them to variables

const student = {

    name: 'Student 1',

    rollNo: 45,

    subject: 'Economics',

    score: 78

};

const { namescore } = student;

console.log(namescore); // Student 1 78

Importing specific things from JavaScript modules

import { ComponentOnInitInput } from '@angular/core';

Spread operator

Spread operator (…) allows an iterable such as an array or string to be expanded in place. Let’s understand this with some examples.

Examples

Printing the values of an array on console

const array = [1234];

// Without spread operator.

console.log(array); // [ 1, 2, 3, 4 ]

// With spread operator.

console.log(...array); // 1 2 3 4

Concatenating two arrays

const a = [123];

const b = [456];

const c = [...a, ...b];

console.log(c); // [ 1, 2, 3, 4, 5, 6 ]

Note that ‘c’ is a completely new array which means spread operator can be used to copy arrays as well.

Shallow copying an object

const a = { id: 1name: 'A'type: 'object' };

const b = { ...a };

console.log(b); // { id: 1, name: 'A', type: 'object' }




Comments

Popular posts from this blog

What are filter, map and reduce functions in JavaScript?

Is competitive programming required to become a good software engineer?