nibble
nibble

Reputation: 404

Using bracket notation on a JavaScript number

I was reading through code submitted by someone on a coding forum. I came across something like 100[0] in his code. I expected JavaScript to throw an error but to my surprise it is undefined. I have known the bracket notation to be used with objects, arrays and strings but it is quite strange that it doesn't throw when used with a number.

Is this similar to invoking a method on a string literal like "FOO".toLowerCase() where the string is first coerced to an object and then toLowerCase is invoked? Can someone explain to me what is going on here?

Upvotes: 0

Views: 687

Answers (1)

Scotty Jamison
Scotty Jamison

Reputation: 13129

While numbers like 12 are primitives in javascript, you can still access properties on it. Take a look at the Number API Reference for what kinds of properties a number has.

For example, (2).toString() will yield '2'. So will 2['toString'](). This should hopefully help explain why such syntax is still valid.

What makes this possible is a technique called "boxing". Most of the time when working with numbers, we aren't accessing properties or methods on the number, so the runtime will just use primitive values to keep things quick. But, the moment we try to access a property like toString() on the number, then a temporary instance will automatically be created for that number so that you can access the property.

This is mostly an invisible process, but artifacts of it are noticeable in the language. For example, comparing two primitives, 2 === 2, is true. But if we force boxing to happen with the Number constructor, new Number(2) === new Number(2), then we'll be comparing two number object, and these objects follow the same rules as any other objects, so this will actually evaluate to false. (Note that we can only observe these kinds of behaviors by force creating the number instances, the auto-boxing will never happen for anything but equality checks).

Upvotes: 1

Related Questions