Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Array(1) and new Array(1) in JavaScript?

Tags:

javascript

I just started thinking about this, but couldn't get any differences to expose themselves whilst mucking around in jsFiddle.

var a = new Array(1),     b = Array(1);  console.log(a, b); 

Output is two arrays with one undefined member.

Doing a for ( in ) reveals they have the same properties.

What are the differences between these? Does the first one simply instantiate the object explicitly?

Please don't lecture me about using array literal notation as I already know about that. I'm more wishing to fill this gap in my knowledge explained above.

like image 892
alex Avatar asked Apr 29 '11 01:04

alex


People also ask

What is the difference between array and new array in JavaScript?

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.

What is the difference between new array and array?

new Array() There are no differences between calling Array() as a function or as a constructor. According to the spec, using Array(…) as a function is equivalent to using the expression new Array(…) to create an Array object instance with the same arguments.

What is new array in JavaScript?

JavaScript Arrays - How to Create an Array in JavaScript. An array is a type of data structure where you can store an ordered list of elements. In this article, I will show you 3 ways you can create an array using JavaScript. I will also show you how to create an array from a string using the split() method.

Does array [- 1 work in JavaScript?

As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).


2 Answers

With Array, both are equivalent. The new is injected when it's called as a function:

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.

From ECMA-262, 3th Edition (with similar in 5th Edition). See also 22.1.1 The Array Constructor in ECMA-262 ECMAScript 2020 specification (11th Edition).

like image 106
Jonathan Lonowski Avatar answered Sep 26 '22 21:09

Jonathan Lonowski


According to Javascript: The Definitive Guide (5th Edition), page 602, "When the Array() constructor is called as a function, without the new operator, it behaves exactly as it does when called with the new operator."

like image 39
Brigham Avatar answered Sep 25 '22 21:09

Brigham