Javascript notes - Part 3 - Array and Object destructuring

Javascript notes - Part 3 - Array and Object destructuring

ES2015 introduced a new feature called destructuring.

We use the "dot" notation is Javascript objects to either assign one property at a time or access one property at a time, like shown below:

let user = {}

user.name = "Shanu Khera"
user.location = "India"
user.profession = "Engineer"

let name = user.name
let location = user.location
let profession = user.profession

Adding multiple values to an object in one go is allowed at initialization time.

let user = {
  name: "Shanu Khera",
  location: "India",
  profession: "Engineer",
}

We can add and access properties one at a time. We can add multiple properties at the same time, but before destructuring, there was no way to extract multiple properties at the same time.

Destructuring Objects

Destructuring allows us to extract multiple properties of an object. This makes our code very readable and convenient to write.

let user = {
  name: "Shanu Khera",
  location: "India",
  profession: "Engineer",
}

/* Without destructuring

let name = user.name
let location = user.location
let profession = user.profession
*/

// With destructuring
// This creates 3 new variables just like commented code.
let { name, location, profession } = user;

A common use case is using a returned object from a function invocation.

function getUser() {
  let user = {
    name: "Shanu Khera",
    location: "India",
    profession: "Engineer"
  }
}

const { name, location, profession } = getUser()

Array destructuring

const arr = ["Shanu", "Engineer"]

/* Without destructuring
const name = arr[0]
const profession = arr[1]
*/

const [name, profession] = arr

Another example

const csv = "Shanu Khera, Engineer, India"
const [name, profession, location] = csv.split(',')

Destructuring with renaming

We can destructure an object and save one or more values in a different variable name than the array property name.

Example -

const user = {
  name: "Shanu Khera",
  location: "India",
  profession: "Engineer",
}

const {name: user_name, location: country, profession} = user

console.log(user_name) // Shanu Khera
console.log(country) // India
console.log(profession) // Engineer

Destructuring and default values

Destructuring is used quite often when we prefer to pass an object as a function argument instead of multiple arguments and thus not worrying about the position of multiple function arguments either.

function awesomeFunc( { name, email, profilePic=DefaultUserPic } ) {
  // do something
}

Destructuring with default values is not limited to just functions.

const { user_name:name, email, isActive=true } = user

If default values are not provided, undefined is the default value.