2

why does browser throw Error for var null; ?

I am reading Javascript Garden-undefined and I know undefined is a global variable different from null.

But I am just curious about that why it throws Error when dovar null;
in contrast, when var Number=123,var Boolean=123,var Object=123,var undefined=123(although useless), etc.,it's ok.

As far as I know, null is not a reserved word and keyword in JavaScript. It should be a primitive type.

How does var work exactly in relation to null?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ye Shiqing
  • 1,519
  • 2
  • 15
  • 24
  • "Additionally, the literals null, true, and false cannot be used as identifiers in ECMAScript." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords – mplungjan Nov 12 '16 at 07:13
  • @mplungjan thank you and it's useful.I don't know NullLiteral, and BooleanLiterals before and it's really a puzzle for me.I want to know why you think it's a duplicate.should I delete this anwser if I got the down vote? – Ye Shiqing Nov 12 '16 at 07:31
  • I tried but I cannot find an official document that says "null" is a _reserved word_ - we all just agree it is and I personally do not care. I never use variable names that MIGHT be reserved. Here is a cool tester: https://mothereff.in/js-variables – mplungjan Nov 12 '16 at 07:35
  • thx all,**I know the question is useless in effect**,but I am just curious about it, I am a curious boy~thank you for all of you. – Ye Shiqing Nov 12 '16 at 07:42

1 Answers1

1

The difference is null is a reserved identifier and undefined isn't.

From the documentation:

The literals null, true, and false cannot be used as identifiers in ECMAScript.

This is part of the grammar definition, while global variables are just things you can (usually) override.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    I don't totally agree with you.null is not a reserved keyword.It's just a literal. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Literals – Ye Shiqing Nov 12 '16 at 07:34
  • 2
    The comment from @mplungjan is also quite specific, and I'll repeat it here: "Additionally, the literals `null`, `true`, and `false` **cannot be used as identifiers** in ECMAScript." There's no such provision for `undefined`. I don't know what you want that's more official than that other than a letter from Eich with a wax seal on it, perhaps? – tadman Nov 12 '16 at 07:36