JavaScript Parameter Destructuring Tutorial

In this section, we will learn what the parameter destructuring is and how to use it in JavaScript.

What is Parameter Destructuring in JavaScript?

Other than assignments, we can use destructuring in function parameters as well.

This means using the properties or elements of an object/array as the values for the parameters of a function.

JavaScript Parameter Destructuring Syntax:

For example:

function func({a,b}){…}

Here, the parameters of this function are basically `a` and `b`. The function takes an object that should have two properties, named `a` and `b`. The execution engine will then assign the values of these two properties to the parameters `a` and `b`.

Example: using parameter destructuring in JavaScript

function func({a,b}){
  console.log(`${a}    ${b}`);
}
func({a:10, b:100})

Output:

10 100

How Does JavaScript Parameter Destructuring Work?

Here we called the `func` function and passed an object that has two properties named `a` and `b` with the values 10 and 100, respectively.

If the object that we set as the argument to the function didn’t have the properties, then the parameters in the `func` function would’ve had the value `undefined`.

Example: JavaScript function parameter destructuring

function func({a,b}){
  console.log(`${a}    ${b}`);
}
func({ b:100})

Output:

undefined 100

The parameter being destructured doesn’t have to be the first one, or the only one; it can be anywhere in the parameter list:

Example: destructuring for the second parameter of a function

function func(first, {a,b}, last){
  console.log(`The first value is: '${first}'' and the last one: '${last}'`)
  console.log(`${a}    ${b}`);
}
func("John",{ b:100}, "Doe")

Output:

The first value is: 'John'' and the last one: 'Doe'

undefined 100

Example: JavaScript parameter destructuring with default values

The destructuring pattern that we set in a function can have a default value as well. This default value will kick in if the input is undefined.

function func(first, {a,b} = {a:100, b:1000}, last){
  console.log(`The first value is: '${first}'' and the last one: '${last}'`)
  console.log(`${a}    ${b}`);
}
func("John",undefined, "Doe")

Output:

The first value is: 'John'' and the last one: 'Doe'

100 1000
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies