2

Can anyone, please explain in simple words why JavaScript expression

123.unexistingProperty;

throws an error, while

var v = 123;
v.unexistingProperty;
(123).unexistingProperty;
true.unexistingProperty;
"".unexistingProperty;
[].unexistingProperty;
{}.unexistingProperty;

do not?

Is this something to do with prototyping or just some rationale of the language?

P.S. Not just hypothetical, this comes up as a question when implementing eval() on dynamically generated code.

asked Apr 4, 2015 at 7:39
2
  • 1
    v.unexistingFunction(); throws Uncaught TypeError: undefined is not a function Commented Apr 4, 2015 at 7:47
  • 1
    i think 123 is constant while v is variable and v has some properties Commented Apr 4, 2015 at 7:48

1 Answer 1

4

Is this something to do with prototyping

No, the reason is that Javascript doesn't allow you to access attributes directly on number literals.

For example this won't work:

123.unexistingProperty;

but this will work:

(123).unexistingProperty;

The thing is that a number can be written in the form of 10.5 Which means that the dot can't be use to access properties. For that reason, you'd have to wrap a number between parenthesis to call a property on the number.

Example:

Number.prototype.fun = function () { return "Fun" }
(100).fun()
(10.5).fun()
answered Apr 4, 2015 at 7:58
Sign up to request clarification or add additional context in comments.

2 Comments

It feels like the last part of this answer is the only piece that makes sense: Use of dot ambiguity, following a number, which then would be just a language rationale.
@vitaly-t pretty much it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.