Premium lesson

Indexed Data Structures in JavaScript II

JavaScript·4 min read·Jan 1, 2025

Destructuring array elements

The destructuring assignment syntax is a shorthand syntax that allows you to extract values from arrays, in order, and assign them to variables in a more concise and structured way:

let [element1, ..., elementN] = array;

Note: When destructuring a property that doesn't exist within the object, the specified variable will hold the undefined value.

Example

Let's consider this script, that outputs the result of a division and its remainder:

const divide = (a, b) => [a / b, a % b];const [result, remainder] = divide(7, 3);console.log('result = ', result);console.log('remainder = ', remainder);

When executed, it will extract the values of the array returned by the divide() function into two distinct variables named result and remainder, and output their values.

Which will produce this output:

result =  2.3333333333333335
icon light bulb key

Unlock the Build CLI Apps in JavaScript & Node.js module

Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.

You get immediate access to:

  • 45 focused lessons across JavaScript, Node.js, npm, and Git
  • 17 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module