Reputation: 728
Maybe I'm asking this incorrectly, but I'm primarily wondering what is the difference between creating an array with and without the "new" keyword? When is it appropriate to use?
var myPix = new Array("Images/pic1.jpg", "Images/pic2.jpg", "Images/pic3.jpg");
I know that the the "new" keyword creates a new object. But, since I'm creating a variable that holds the array object, isn't the array still created without using "new"?
Lastly, couldn't I just as easily use this?
var myPix = ["Images/pic1.jpg", "Images/pic2.jpg", "Images/pic3.jpg"];
Upvotes: 4
Views: 3811
Reputation: 10891
We don't need the new
keyword for Array()
because is has "exotic" behavior mandated by the ECMAScript standard:
The Array constructor:
...
- creates and initializes a new Array when called as a constructor.
- also creates and initializes a new Array when called as a function rather than as a constructor. Thus the function call
Array(…)
is equivalent to the object creation expressionnew Array(…)
with the same arguments.
Upvotes: 2
Reputation: 4824
You can do this either way.
In JavaScript, everything is an object including arrays and a typical way to instantiate is to use the keyword new. But, for a few cases including array, this can be avoided by declaring an array like this:
var arr = [3,45,43,4];
however, the second way (using []
) of creating an array is preferred because:
See discussion here - Why is arr = [] faster than arr = new Array?
Upvotes: 0
Reputation: 95242
In Javascript, "classes" are really their own constructor/initializer functions. The Array
function is an example. When you call new Array
, Javascript first creates an uninitialized object, and then invokes Array()
with that new object as this
. If you run Array()
without the new
, you're skipping to that second step without creating any object to initialize.
With its built-in type functions like Array
, Javascript will turn around and create the object for you even when called without new
; they "do the right thing" because they're written that way. Your own type functions won't be so considerate unless you go out of your way to code them so.
In general, if you're looking for shorthand notation, you should just use the bracket form.
Upvotes: 4
Reputation: 927
using new Array("a", "b", "c") is equivalent to ["a", "b", "c"]. The latter is called Javascript Object Notation and is more script-like ala languages such as python. The returned object is still an Array in either case.
Upvotes: -2