Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for destructuring arrays into function parameters in ES6

There is plenty of documentation on how to destructure objects passed as function parameters in Javascript 2015 / ES6 / ECMAScript 2015, with a function like this:

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

But how do you destructure an array parameter?

like image 521
JBCP Avatar asked Apr 30 '16 22:04

JBCP


People also ask

What is the correct syntax for Destructuring arrays in JavaScript?

The Syntax with Destructuring. var first = "laide", second = "Gabriel", third = "Jets"; The Syntax Without Destructuring. You cannot use Numbers for destructuring.

What is array Destructuring in es6?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

What is parameter Destructuring?

Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required.

Can we Destructure function in JavaScript?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays.


1 Answers

The correct syntax to destructure an array parameter is:

function foo([a, b]) {    console.log(`param1: ${a}, param2: ${b}`); } 

It can be called like this:

 foo(['first', 'second']);  // Will output:  // param1: first, param2: second 

According to Exploring ES6, section 11.6, you can use this to destructure parameters within arrow functions as well:

const items = [ ['foo', 3], ['bar', 9] ]; items.forEach(([word, count]) => {     console.log(word + ' ' + count); }); 
like image 131
JBCP Avatar answered Sep 23 '22 05:09

JBCP