Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Destructuring

Destructuring Assignment Syntax

The destructuring assignment syntax extracts object properties and assigns them to variables.

let {firstName, lastName} = person;

It can also extract values from arrays and other iterable objects.

let [firstName, lastName] = person;

Object Destructuring

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50
};

// Destructuring
let {firstName, lastName} = person;

The order of the properties is not important.

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50
};

// Destructuring
let {lastName, firstName} = person;
Note:
Destructuring is non-destructive; it does not modify the original object.

Object Default Values

We can set default values for properties that may be missing.

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50
};

// Destructuring
let {firstName, lastName, country = “US”} = person;

Object Property Alias

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50
};

// Destructuring
let {lastName : name} = person;

String Destructuring

One application of destructuring is extracting characters from a string.

Example

// Create a String
let name = “W3Schools”;

// Destructuring
let [a1, a2, a3, a4, a5] = name;
Note:
Destructuring can be applied to any iterable.