1252748
1252748

Reputation: 15379

Strange use of square braces to call functions

How does calling functions with square braces work?

100['toString']//function toString() { [native code] }
100['toString']['length']//1

What exactly is happening here?

Upvotes: 3

Views: 170

Answers (3)

dfsq
dfsq

Reputation: 193301

This is bracket notation. Any property can be accessed using either dot- or bracket notation. So since toString is a property, you can access it using bracket notation.

For number you can however also use dot-syntax, but you have to make clear to parser that the dot is not a decimal point. For example with two dots:

100..toString() // equivalent to 100.0.toString

To avoid this confusing syntax for numbers, bracket version is preferred. But in most cases dot-notation allows more concise and cleaner syntax, although you can always use brackets when you can use dot.

The benefit of the bracket-syntax is that:

  • it should be used to access properties with the name stored in variable
  • it allows to access properties with the names that are not valid identifiers.

And the answer to the second question.

why does 100['toString']['length'] not evaluate to three?

Because 100['toString'] is a method inherited from the Number.prototype. Hence this is a function. And the length property of the function is the number of explicit arguments it accepts. Number.prototype.toString takes a radix parameter, the only one. So the result is 1.

Upvotes: 6

Jonathan Gray
Jonathan Gray

Reputation: 2609

Everything in JS is an object with potential properties. Accessing a method can be done the same as using the key name in the object. Square brackets can be used on numbers where decimal points cannot as they would be interpreted as part of the number. That's just using the alternative option of calling the Object property toString on a Number object.

Upvotes: 1

Scimonster
Scimonster

Reputation: 33409

It's not calling any function at all. It's just accessing the properties using bracket notation.

Dot notation doesn't work for integers, because the compiler apparently doesn't want to test if it's a float or identifier. So, 100.toString is a syntax error.

Upvotes: 0

Related Questions