Why by "new Array" after the variable?

1

Why put new Array after the variable name?
Example:

var weatherPattern = new Array('Clouds', "raining", "clowdy");
    
asked by anonymous 26.07.2017 / 18:06

1 answer

4

This is a way to declare a array in JavaScript, you call a function Array() that should just generate the array to assign to the variable. The new is used to indicate the object's allocation. It has no secret, it is the same as other non-primitive objects.

There is a 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 using the literal, as shown below, the effect is the same, so if used so it should be a style question. Otherwise it would 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];

The first creates an array and reserves 5 positions to allocate objects, the second creates an array with a numeric element that is 5, are quite distinct things. In this case the argument passed to the Array() function does not behave as an array element but rather as a configuration parameter of the array size.

There's another catch. The Array() function can do something different than expected since JS allows it to be overwritten. It may even create an array . Of course no programmer should do this, but he can. This is an interesting trick.

JavaScript has these same quirks.

    
26.07.2017 / 18:23