This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 7 years ago.
var a,b,c;
var arr = [1,2,3];
[a,b,c] = arr;
this code works perfectly in Firefox resulting a=1, b=2 and c=3,
but it doesn't work in Chrome. Is it a Chrome bug or
it is not valid javascript code? (I failed to find it in javascript references)
How can I modify this code to make it suitable for Chrome, with minimum damage to it?
(I don't really like to write a = arr[0]; b = arr[1]... or the same with arr.shift() all the time)
P.S. this is just an example code, in real code
I get the arr array from somewhere outside my code
This is a new feature of JavaScript 1.7 called Destructuring assignment:
Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.
One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.
You can use destructuring assignment, for example, to swap values:
var a = 1;
var b = 3;
[a, b] = [b, a];
This capability is similar to features present in languages such as Perl and Python.
Unfortunately, according to this table of versions, JavaScript 1.7 has not been implemented in Chrome. But it should be there in:
FireFox 2.0+
IE 9
Opera 11.50.
Try it for yourself in this jsfiddle: http://jsfiddle.net/uBReg/
I tested this on Chrome (failed), IE 8 (failed), and FireFox 5 (which worked, per the wiki table).
It is possible only for Javascript 1.7 as already answered by #Justin. Here is a trial to simulate it in the widespread browsers:
function assign(arr, vars) {
var x = {};
var num = Math.min(arr.length, vars.length);
for (var i = 0; i < num; ++i) {
x[vars[i]] = arr[i];
}
return x;
}
var arr = [1, 2, 3];
var x = assign(arr, ['a', 'b', 'c']);
var z = x.a + x.b + x.c; // z == 6
I don't know how useful it is.
Related
This question already has answers here:
What is this JavaScript syntax: {Ci, CC}? [duplicate]
(2 answers)
Closed 7 years ago.
EDIT
After looking at JSHint I found this 'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz) and this however after reading it I still don't understand why it is used
I have come across the following code on MDN
var ui = require("sdk/ui");
var { ActionButton } = require("sdk/ui/button/action");
What do the braces on the second line do and why are they used? Why are there no braces on the first line?
This is what's known as a destructuring assignment, and it's a new feature of JavaScript 1.7 (and ECMAScript 6) (Currently, only available as part of the Firefox JavaScript engine.) Roughly, it would translate into this:
var ActionButton = require("sdk/ui/button/action").ActionButton;
It seems silly in this example, as there's only one item being assigned. However, you'd be able to use this pattern to assign multiple variables at once:
{x, y} = foo;
Is the equivalent to:
x = foo.x;
y = foo.y;
This can also be used for arrays. For example, you could easily swap two values without using a temporary variable:
var a = 1;
var b = 3;
[a, b] = [b, a];
Browser support can be tracked using kangax' ES6 compatibility table.
This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 5 years ago.
I'm a beginner to Javascript and encountered this syntax usage(simplified):
var testString ="firstName, lastName";
var [a,b] = testString.split(", ");
My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.
But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.
But what goes on under the hood?
// You declare a string variable
var testString = "firstName, lastName";
// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
Since the split function returns an array, with the var [a,b] = array
you are assigning the value in index order, in the example:
console.log(a); // 'firstName'
console.log(b); // 'lastName'
And they are simple string variables. You may want to vist the links below:
Destructuring asignation
split function
Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post
This is destructuring assignment. It resembles the pattern-matching found in many functional languages.
This question already has answers here:
Destructuring to get the last element of an array in es6
(17 answers)
Closed 5 years ago.
I just discovered the delightful ES6 destructuring syntax for lists, i.e.
ls = [1, 2, 3]
[first, ...rest] = ls
which sets first to 1 and rest to [2,3]. However, is it possible to split the list into rest=[1,2] and last=3 using similar syntax?
I didn't have any luck googling it. I tried some obvious guesses for such a syntax (see below), but they all produced syntax errors.
[rest..., last] = ls
[...rest, last] = ls
I suppose I could do it by reversing the list twice, so an alternate solution to my question would be a constant time list reversal function.
What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:
const [...first, last] = integers();
because integers could be
function* integers() {
let n = 0;
while (true) yield n++;
}
and then what would last be?
No, this only works on trailing array elements. So, as you said, they way to achieve what you want would be reversing the array first.
Just in case you haven't come across a similar pattern for object, there is one:
const {a, ...rest} = {a: "prop1", b: "prop2", c: "prop3"}
A great tool to try all this new features out is https://babeljs.io/repl
This question already has answers here:
Copy array by value
(39 answers)
When I assign a variable to another variable does it not link them together?
(1 answer)
Closed 9 years ago.
I have really weird situation:
when I do that code:
var origin_array = [1,2,3];
var m = origin_array;
m.pop();
alert(origin_array);
origin_array value will be 1,2
eventhough I didn't changed it
but if I make that code:
var x = 5;
var y = x;
y--;
alert(x);
x still be 5, it won't be connected to "x" as you can see from the 1st example.
So my question is how do I make the "m" array unique, which not change the origin array?
You need to explicitly make a (shallow) copy or clone of origin_array:
var m = origin_array.slice(0);
This is not needed for primitive values, such as strings and numbers.
It's important to understand that although the above will prevent the issue you were experiencing, the same may happen again deeper down if you're dealing with more complex structures, and in some cases a "deep clone" is necessary.
Arrays are assigned by reference. That means that when you do this:
var origin_array = [1,2,3];
var m = origin_array;
m just points to the exact same array as origin_array. There is only one array and both origin_array and m point to it. If you modify it via either variable, they will both see the modification because you're modifying the one array that they both point to.
In javascript, both objects and arrays are assigned by reference like this. Assigning them does NOT make a copy. If you want an assignment to generate a copy, you have to explicitly make a copy. For an array, that is easy as you can just do:
var origin_array = [1,2,3];
var m = origin_array.slice(0); // makes a shallow copy
m.pop();
console.log(origin_array); // [1,2,3] because origin_array was not changed
This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
What is the difference between `new Object()` and object literal notation?
(12 answers)
Create an empty object in JavaScript with {} or new Object()?
(10 answers)
Closed 5 years ago.
Is it better to write
var arr=[]; then var arr=new Array();
var obj={}; then var obj=new Object();
and if so, why?
I read slide lection page 36 about that idea, but no explanation was given or example why its better.
There is not a big difference between these definitions, except that the first way uses the array/object literal and the second the array/object constructor.
The array constructor may return different results, depending on the number of arguments passed in. If you pass in one argument, a new empty array is created of the length of that argument. For example:
// arr1 is the same as arr2
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];
alert(arr1.length == arr2.length); // true
alert(arr1[0]); // 1
alert(arr2[0]); // 1
But, passing in one argument results differently:
// arr3 has length 200 and is empty, while arr4 has length 1 and contains a number
var arr3 = new Array(200);
var arr4 = [200];
alert(arr3.length == arr4.length); // false
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200
The speediest way to define an array or object is of course the literal way, because you don't need to call the constructor first. Anyway, the actual speed difference is negligible, really.
I did a speed test in Chrome 6, in which I defined 20 times 10000000 the same array 1, 2, 3, which gave these results:
Average speed per 10000000 calls
Array Constructor : 226.55 ms
Array Literal : 159.1 ms
As you can see, the array literal is 67,45ms faster per 10000000 array definitions.
From a typical programmer perspective, it seems that you tend to use var arr = new Array(); so as to give the feeling of typical object instantiation. But in javascript its usually good practice to use var arr = [];
Personally I dont see much difference in using both ways except for one parameter which is explained by Harmen.
Check this link too -
http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/
thomas fuchs says in his slideshow, under that video (the part saying "embrace the language" on page 20):
var arr=[] and var obj={} is better and slightly faster. I'm not sure why, but anyway, it's a pretty interesting slideshow :)