What is the difference in Javascript between 'undefined' and 'not defined'?

前端 未结 8 2221
半阙折子戏
半阙折子戏 2020-11-29 03:21

If you attempt to use a variable that does not exist and has not been declared, javascript will throw an error. var name is not defined, and the script will sto

8条回答
  •  旧巷少年郎
    2020-11-29 03:53

    JavaScript provides several different notions of missing or empty variables (and object properties):

    1. Variables that are actually 'not defined', i.e. they don't exists as a given name isn't bound in the current lexical environment. Accessing such a variable will throw an error, but using typeof won't and will return 'undefined'. In contrast, accessing non-existing properties will not throw an error and return undefined instead (and you may use the in operator or the hasOwnProperty() method to check if properties actually do exist).

    2. Existing variables which have not been assigned a value (which is common because of var hoisting) or which have been explicitly set to undefined. Accessing such a variable will return undefined, typeof will return 'undefined'.

    3. Existing variables which have been explicitly set to null. Accessing such a variable will return null, typeof will return 'object'. Note that this is misleading: null is not an object, but a primitive value of type Null (which has the consequence that you can't return null from constructor functions - you have to throw an error instead to denote failure).

    I'd recommend the following practices:

    1. Use typeof to check for undefined, as it will cover the first two cases.
    2. Don't assign undefined to properties: Use delete to get rid of them instead; note that you cannot delete variables (but also note that globals are actually properties of the global object and thus can be deleted).
    3. Use null to mark the absence of a meaningful value (eg the forward reference of the last node of a linked list) or if you want to clear a variable as a hint to the garbage collector.

    You could go with undefined for 3. as well and never use null at all.

提交回复
热议问题