Search code examples
javascriptarraystypescastingvar

What does the "var" before a JavaScript array initialization refer to, the elements of the list or the array itself?


I was taught to use "let" to initialize arrays in JavaScript, but I've recently discovered that "var" can be used as well.

var evenNumbers=[2,4,6,8];

I know that it's possible to initialize a function in JavaScript using var, as in

var hello=function(){};

so naturally, I assumed that the "var" being used to initialize the variable refers to the name of the array, in this case evenNumbers.

However I also recently learned that to initialize arrays in C, which I think of as the grandfather of Java-type languages, the type of variable used in the array is used to initialize the array call.

int evenNumbers[]={2,4,6,8};

Obviously in this case, int refers to the elements of the list, since an array is not an int.

I therefore assumed that var before an array call in JavaScript refers to the elements of the list. I tried to test it by applying the wrong strong type to a new JavaScript variable, like

int newYearsResolutions=["Stop procrastinating"];

Which gives me an unexpected identifier, but that's not too helpful since an array is not an int nor is "Stop procrastinating" an int. I then tried

int evenNumbers=[2,4];

and this gives me the same error, leading me back to my original conclusion that the var being named here is "evenNumbers" and not the ints 2 and 4, but I still feel like I might be missing something.

So, var evenNumbers=[2,4] appears to name the evenNumbers variable and not the elements of the array. I just want to double-check that that's the case.


Solution

  • JavaScript is not a typed language. int isn't a reserved word, and thus is not doing anything. var, let, const are all ways to assign variables - regardless of type.