1

I seen a code snippet like the below. Can anybody please tell me what

var [input] = data; var [checkbox, payee, amount]  = data2;

means?

function example(data,data2){
var [input] = data;
var [checkbox, payee, amount]  = data2;
............
............
}
Vino
  • 304
  • 1
  • 3
  • 12
  • Possible duplicate of [Square Brackets Javascript Object Key](https://stackoverflow.com/questions/32515598/square-brackets-javascript-object-key) – CBroe Jan 17 '18 at 11:55
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – CBroe Jan 17 '18 at 11:56
  • 1
    it's a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) by taking an array as value to assign – Nina Scholz Jan 17 '18 at 11:56

4 Answers4

2

As Nina Scholz stated in her comment, it's a destructuring assignment.

If data2 was an array of [1, 2, 3], then var [checkbox, payee, amount] = data2; is the same as:

    var checkbox = data2[0]; // 1
    var payee = data2[1]; // 2
    var amount = data2[2]; // 3

Rest parameter

You can using destructuring with rest parameter like in the example below, to save multiple elements into an array.

const digits = [1, 2, 3, 4, 5];
const [one, ...other] = digits;
console.log(one);
console.log(other);

Omitting values

You can ignore the values you're not interested in, like this:

const myArray = ["car", "cat", "house", "dog", "window", "mouse"];
const [, cat, ,dog, , mouse] = myArray;
console.log(cat, dog, mouse);

or like this:

const myArray = ["John", "Mary", "Steve", 0, 1, 2];
const [name1, name2, name3] = myArray;
console.log(name1, name2, name3);
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18
1

This is just the destructuring assignment

var t = [1,2];

var [a,b] = t;

console.log(a);
console.log(b);

When used on arrays, it assigns consecutive array elements to variables introduced at the left side of the assignment operator.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
1

It's a destructuring assignment with an array/iterable object (with implemented Symbol.iterator) with values to assign.

The value goes into the variable with the same index as the given data.

For getting only some parts at a certain index, you could use an object with indices as keys.

var array = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
    [zero, one] = array,
    { 3: three, 10: ten } = array;
    
console.log(zero);
console.log(one);
console.log(three);
console.log(ten);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This is Destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

As per your example,

var data = [1];
var [input] = data;
console.log(input); //1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94