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

前端 未结 8 2083
半阙折子戏
半阙折子戏 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:44

    An undeclared variable (that is, one that doesn't exist) does not have a type - and so its type is undefined. I believe that the generally accepted way to test if something is undefined is

    typeof var === 'undefined'
    

    rather than

    var === undefined
    

    since if the variable does not exist, you cannot access it. The latter case might be more useful if you are sure the variable should exist, since the difference between the two is that an undeclared variable will return false in the first case but cause an error in the second case.

    Make sure that you use the triple-equals operator though if you're using the second variant; the (more usual) double-equals operator performs type coercion, so null == undefined is true while null === undefined is false. Sometimes you might want the first behaviour, though often you'll want the second, especially if you're testing against undefined, so it's important to recognise the difference. (This is another benefit of the first case since it's not possible to make this subtle error).

    Yes, variables can have a value of undefined and you can explicitly assign values to them. Assigning undefined to a variable though is probably confusing, since it's a bit of a paradox (you've defined the variable as undefined) and it's not possible to distinguish that variable from either variables that don't exist or uninitialised variables. Use null if you want to signify that a variable has no value currently, or if you want to "undeclare" the variable altogether, use delete {varname}. Assigning undefined to a variable does not remove that variable's declaration; and it will still appear in the list of its owning object's properties if you iterate over them, so I can't think of any situation this would benefit you.

    Edit: In response to the comment, when comparing the values with === (or ==), the variable must be deferenced to obtain its current value in order to do the comparison. Since the variable doesn't exist, this dereferencing fails (no real surprises so far). While you might expect the typeof operator to work in a similar way (get the current value, see what its type is) it specifically works with undefined variables. The "short version" (as used by the Mozilla reference ) is simply that "The typeof operator returns a string indicating the type of the unevaluated operand."

    The long version, extracted from the ECMAScript spec, is that there's a special case for undefined variables:

    11.4.3 typeof UnaryExpression is evaluated as follows:

    1. Evaluate UnaryExpression (as per 10.1.4 this returns "a value of type Reference whose base object is null and whose property name is the identifier" if the variable is undeclared).
    2. If Type(Result(1)) is not Reference, go to step 4. (It is a Reference)
    3. If GetBase(Result(1)) is null, return "undefined". (This is the special case matching undefined variables)

    As for your comment to the first question, "how can you classify what does not exist" - it's easy! Simply divide all concepts into things that do exist (e.g. squirrel, rock) and those that don't exist (unicorns, warp drives). That's what undefined means; regardless of its semantics in English, its Javascript meaning is that the variable hasn't been declared or populated yet, and so while the concept of "a variable called foo" is valid, there exists no variable with that name holding a real value.

    0 讨论(0)
  • 2020-11-29 03:51

    An undeclared variable does not exist in Javascript memory whereas a declared one does and can be set to undefined.

    The difference is caused by Javascript design confusion. If a variable's value is undefined then it should be deleted. Indeed falsy values like 0, "", null, and undefined, are all basically meaningless and identical. A lot of time is wasted on them. They are all nothing and non existent. It is highly contradictory to have more than one type of nothing, or maybe to allow even one.

    Therefore I think you should avoid explicitly using falsy values when programming altogether. I didn't find a case yet when they couldn't be eliminated by a better method, and programming is much nicer without them.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 03:53

    Not defined:

    Variable is not declared or initialized. Throws reference error

    Example:

    console.log(newvariable); // results: ReferenceError: newvariable is not defined
    

    Undefined:

    A variable declared without a value will have the value undefined.

    Example:

    var newVar;
    console.log(newVar); // results: undefined
    
    0 讨论(0)
  • 2020-11-29 03:56

    I believe it's a difference between JavaScript definition and firebugs of the same thing.

    Undefined is just the state of something that has not been defined as a value. So it has no type.

    Also what is the difference between var a; and var b = undefined;

    var a; alert(a); // undefined
    a; alert(a); // "Error "a" not defined"
    a = undefined; alert(a); // undefined
    

    2nd example is not valid JavaScript code and the execution will stop. Since this is an error.

    0 讨论(0)
  • 2020-11-29 03:56
    • not defined - instance is not declared and used;
    • undefined - instance declared and used without it value.
    0 讨论(0)
提交回复
热议问题