2
Why put new Array
after the variable name?
Example:
var weatherPattern = new Array('Clouds', "raining", "clowdy");
2
Why put new Array
after the variable name?
Example:
var weatherPattern = new Array('Clouds', "raining", "clowdy");
5
This is one way to declare a array in Javascript, you call a function Array()
which should precisely generate the array to assign to the variable. O new
is used to indicate the object allocation. It has no secret, it is the same as other nonprimitive objects.
There is the syntax where the array is created as a literal in the language. The effect is the same and becomes more concise and even more readable.
In this example I do not see why not use the literal, as shown below, the effect is the same, so if they used it should be a matter of style. Otherwise I’d have to ask who did it, because technically it’s the same thing.
var weatherPattern = new Array('Clouds', "raining", "clowdy");
var weatherPattern = ['Clouds', "raining", "clowdy")];
In some JS interpreters it may be that one works faster than another, but this is not always guaranteed.
But the following are different:
var weatherPattern = new Array(5);
var weatherPattern = [5];
I put in the Github for future reference.
The first creates a array and reserves 5 positions to allocate objects, the second creates a array with a numeric element worth 5, they are very different things. In this case the argument passed to the function Array()
does not behave as an element of array and yes as a size setting parameter array.
There’s one more trick. The function Array()
can do something different than expected since JS allows it to be overwritten. It may not even create a array. Of course no programmer should do this, but it can. Which is still a possible interesting trick.
Javascript has these oddities even.
Browser other questions tagged javascript array oop variable-declaration
You are not signed in. Login or sign up in order to post.
Why not put it? What’s the point of the question? Give more details, context than you want to know. Are you willing to compare it to some other way?
– Maniero
I see an example where the person creates an array and before the array puts that
new Array
, wanted to know if there is any meaning or put by.– Jota