What happens if you declare an array without New in Javascript? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the difference between Array(1) and new Array(1) in JavaScript?
In javascript, how are these two different?
var arr = Array();
var arr2 = new Array();
If they are the same according to JS standards, are there any browsers that treat both ways differently?

According to ECMA-262 edition 5.1:
15.4.1 The Array Constructor Called as a Function
When Array is called as a function rather than as a constructor,
it creates and initialises a new Array object.
Thus the function call Array(...) is equivalent to the object creation
expression new Array(...) with the same arguments.
The section 11.1.4 (it is quite long, so I won't quote it) also states that array literal directly corresponds to the new Array(...) constructor call.

I believe the 2nd is simply proper coding convention, but however Jared has a good point that most people just use var arr = [];
Here's a benchmark for your question: http://jsperf.com/array-vs-new-array
After 10 runs, they're neck and neck averaging 65-80 millions ops per second. I see no performance difference whatsoever between the two.
That being said, I added var arr = []; to the benchmark, and it is consistently 20-30% faster than the other two, clocking in at well over 120 million ops per second.

Related

Creating array of arrays different behavior [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 6 years ago.
I have found that these two different methods of creating an array of arrays produce different behaviors:
// Method 1
for (var arr1 = []; arr.push([]) < len;) {}
// Method 2
var arr2 = new Array(len).fill([])
The arrays created look the same in the console, however they behave differently in my code. What could be causing this?
The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.
Note: the 1st method will not create an array of arrays
var len = 3;
var arr1 = [];
// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1
// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array
arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2
console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Update: While the answer below is technically accurate, and is another difference between the two methods, #Ori Drori's answer is almost certainly what the OP is looking for.
I'll take a stab at this, but more context would be helpful.
In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.
If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.
As an example, let's say I wrote the following code:
function Array() {
}
Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.
Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.

Hard Copy vs Shallow copy javascript [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
This may be an old question but I'm really curious about the nature of copying objects by reference as an assignment in javascript.
Meaning that if
var a = {};
var b = a;
a.name = "Renato";
console.log(b);
Object {name: "renato"}
I'm kind of new to javascript and this really caught my attention to have a shallow copy as a default for Object assignment. I searched that in order to create a hard copy, you have to create a mixin. I was wondering why was this chosen as the default since it's transformation seems to be very implicit. Thanks!
Objects and arrays are treated as references to the same object. If you want to clone the object, there are several ways to do this.
In later browsers, you can do:
var b = Object.assign({}, a);
If you want to go for a library, lodash provides _.clone (and _.cloneDeep):
var b = _.clone(a);
If you don't want to do either of those methods, you can just enumerate through each key and value and assign them to a new object.
Oftentimes it's valuable for them to be treated as references when passing through multiple functions, etc. This isn't the case for primitives like numbers and strings, because that would feel pretty counterintuitive in most cases.

What benefit do you get in javascript declaring an array with a specific length? [duplicate]

This question already has answers here:
How to initialize an array's length in JavaScript?
(20 answers)
Closed 8 years ago.
In most javascript apps I usually declare an array like so
var x = [];
but I've seen a ton of example code on MDN that take this approach instead
var x = new Array(10);
With V8/other modern JS engines, do you see a real benefit one way or the other?
None. Javascript doesn’t implement real arrays. It all gets abstracted through javascript object notation.
So say:
a = [0, 1];
b = {"0": 1, "1": 1};
Has the same effect:
a[0] //0
b[0] //0
One more thing to keep in mind is when you do:
a[100] = 100;
The length gets automagically set to 101. Even though:
a[2] //undefined

Javascript. Swap two variables. How it works? [duplicate]

This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
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.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.

Putting items in JavaScript arrays on arbitrary indices [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are Javascript arrays sparse?
Is the following "safe" in JavaScript? (as in, can be expected to work reliably on all JavaScript engines)
a = [];
a[100] = "hello";
a[100] == "hello"; // should be true
Yes. Arrays in JavaScript are sparse and your code is expected to work in all JavaScript implementations.
You can get into requirements in the section 15.4 of the specification(PDF).
Short summary: array is special object that have length property adjusted when one adds elements at properties with numeric names (like `a[123]="test"). Other methods like join take length into account duuring operations.
Yes, why wouldn't it work? Its perfectly acceptable syntax.
You can even assume
a[100] === "hello"; // will return true

Categories

Resources