190

This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.

In python I can do this:

arr = ['one', 'two']
one, two = arr

how do I do that in JavaScript?

10 Answers 10

246

ES6 allows for destructuring assignment:

let [x, y] = ['foo', 'bar'];
console.log(x); // 'foo'
console.log(y); // 'bar'

Or, to stick to your initial example:

var arr = ['one', 'two'];
var [one, two] = arr;

You could also create a default value:

const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one); // 1
console.log(two); // 2
console.log(three); // 'three'
Sign up to request clarification or add additional context in comments.

2 Comments

destructuring assignment has full support as of today kangax.github.io/compat-table/es6/#test-destructuring
not true, now can be done with the spread syntax: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
33

The question is rather old but I like to post this alternative (2016) solution: One can also use the spread operator "...".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

let xAndY = [42, 1337];
let f = function(x, y) { return x + y; };
f(...xAndY);

Comments

31

That's destructuring assignment. You can do it in some browsers with the following syntax:

[one, two] = arr;

It's supported in some of the latest browsers and transpilers like Babel and Traceur. This was a feature introduced with ECMAScript 4 which later became ECMAScript Harmony, which eventually became ES 2015.

2 Comments

Looks like it's part of ES6 (2015), not ES4? ecma-international.org/ecma-262/6.0/…
@jab: thanks! sometimes these old answers get forgotten about and become outdated, though it looks like Mathias already added that info to his answer :)
7

You can use array's apply function if you want an array items to be passed as a function arguments.

1 Comment

I'm not sure a JavaScript Array has an .apply() function. I think you meant some_function.apply(this, my_array). See this answer
6

Implementation of serious's idea.

http://jsfiddle.net/RichAyotte/6D2wP/

(function(a, b, c, d) {
    console.log(a, b, c, d);   
}.apply(this, ['a', 'b', 'c', 'd']));

1 Comment

This one made my day. Unpacking lists via apply, well done sir!
3
var one = arr[0];
var two = arr[1];

3 Comments

You should really use var to prevent the variables from polluting the global scope.
I'm just assuming its all declared variables :)
It’s probably a better idea to declare all var s for each scope in one go rather than having two separate var declarations.
3

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

Here is an example. You can try like this.

 let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

Comments

2

CoffeeScript has it: http://jashkenas.github.com/coffee-script/#pattern_matching

And, quoted from the top of the page:

"CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it's just another way of saying it."

2 Comments

This doesn't answer the question. I appreciate that CoffeeScript has some neat things, but the question is about Javascript.
Dead link :((((
0

My example works for your example but also if you dont know the array or the array length.

arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
   var val = arr[i];
   eval('var '+arr[i]+'= arr[i];');
}

Know you have 2 variables. The first is 'one' who is "one"and the second is 'two' who is "two". Your problem is solved! But for the code snippet, i created extra elements to display the var's and i logged it.

arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
   var val = arr[i];
   eval('var '+arr[i]+'= arr[i];');
}
var p = document.createElement("p");
p.innerHTML = one + " " + two;
document.body.appendChild(p);
console.log(one, two);

Comments

0
arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
   var val = arr[i];
   eval('var '+arr[i]+'= arr[i];');
}
var p = document.createElement("p");
p.innerHTML = one + " " + two;
document.body.appendChild(p);
console.log(one, two);

1 Comment

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.