Vino
Vino

Reputation: 304

Meaning of var [foo] = bar?

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;
............
............
}

Upvotes: 1

Views: 1384

Answers (4)

Tomasz Bubała
Tomasz Bubała

Reputation: 2153

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);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386710

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);

Upvotes: 1

Wiktor Zychla
Wiktor Zychla

Reputation: 48279

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.

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

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

Upvotes: 0

Related Questions