I am new to JavaScript. From some tutorials I know in javascript there are two ways to declare the array.
One is like this:
var test = new Array("apple","pine");
or
test = new Array("apple","pine");
Two are like this,
var test=["apple","pine"];
but when i use this way to declare it:
test=Array("apple","pine");
It is still ok. why?
In Javascript, you may (and should) declare a variable using the
varkeyword, but it’s not required. So any variable can be declared like this:or
But the first one (with
var) should always be used when you’re creating a new variable. Otherwise, you might be overwriting an already existing variable with the same name. An array is also a variable, so it too can be declared either with or without thevarkeyword. Then there are two ways to declare an array, and both do exactly the same thing:does the same as:
and the
newkeyword, in this case, is not required – as per the javascript specification. But it’s usually used to indicate that you’re creating a new instance of an object.