What is the difference between null and undefined in JavaScript?

前端 未结 30 3876
夕颜
夕颜 2020-11-21 23:06

I want to know what the difference is between null and undefined in JavaScript.

30条回答
  •  野的像风
    2020-11-21 23:36

    I want to add a very subtle difference between null and undefined which is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:

    • null is a reserved keyword in JS while undefined is a variable on the global object of the run-time environment you're in.

    While writing code, this difference is not identifiable as both null and undefined are always used in RHS of a JavaScript statement. But when you use them in LHS of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:

    var null = 'foo'
    

    It gives below error:

    Uncaught SyntaxError: Unexpected token null

    While below code runs successfully although I won't recommend doing so in real life:

    var undefined = 'bar'
    

    This works because undefined is a variable on the global object (browser window object in case of client-side JS)

提交回复
热议问题