Decompose objects and arrays with JavaScript

Learn how to deal with arrays and objects in JavaScript using destructuring syntax

Given an object, using destructuring syntax, you can just extract some values and put them into named variables:

const person = {
  firstName: 'Tom',
  lastName: 'Cruise',
  actor: true,
  age: 54 //made up
}

const { firstName: name, age } = person //name: Tom, age: 54

namewithageContains the required value.

This syntax also applies to arrays:

const a = [1, 2, 3, 4, 5]
const [first, second] = a

This statement creates 3 new variables by getting the items with index 0, 1, 4 from the arraya:

const [first, second, , , fifth] = a

Download mine for freeJavaScript beginner's manual


More js tutorials: