I came across this by mistake one day while programming a game:
var foo = function() { alert("Hello, World!"); } foo[0] = "Zero"; foo[1] = "One"; foo[2] = "Two"; foo[3] = "Three"; foo(); // Alerts "Hello, World!" alert(foo[2]); // Alerts "Two"
Why does JavaScript let you do this? Is this a glitch?
The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.
To overcome this problem, JavaScript provides an array. An array is a special type of variable, which can store multiple values using special syntax. Every value is associated with numeric index starting with 0. The following figure illustrates how an array stores values.
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.
Global variables live until the page is discarded, like when you navigate to another page or close the window. Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.
There are no arrays here. For example, Array.isArray(foo)
is false.
Instead, you are giving foo
four properties, named "0"
, "1"
, "2"
, and "3"
[1], with different values. This is completely valid, because functions are objects; you can always attach properties, with whatever name you like, to objects.
You could also do:
foo.otherProp = "hi!"; alert(foo.otherProp);
[1]: Note that property names are always converted to strings before setting them; doing foo[{ toString: function () { return "baz"; }] = 5
will be the same as foo["baz"] = 5
or foo.baz = 5
. Similarly, doing foo[0] = "whatever"
is the same as doing foo["0"] = "whatever"
.
Why does JavaScript let you store an array and a function in one variable?
It doesn't. It lets you store a reference to a function in a variable. Functions are first-class objects in JavaScript, and so they can have properties, including ones with names like "0"
, "1"
, etc.
You're seeing a couple of things at play here:
What I said above, functions are objects, and so you can add properties to them.
You can add properties ad-hoc, there's no need to predefine them as in some other languages.
In JavaScript, you can refer to a property using dot notation and a literal (foo.bar)
, or using bracketed notation and a string (foo["bar"]
).
When you use bracketed notation, the thing within the brackets is cast to a string if it isn't already one, so [0]
is actually ["0"]
.
And yes, that last is true even when you're dealing with arrays, because standard arrays in JavaScript aren't really arrays. (There are recent additions, Int32Array
and such, which are true arrays, but Array
is not.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With