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

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

    alert(a);

    Here a is not defined.

    alert(a);
    var a=10;

    Here a is undefined because javascript engine convert this code to

    var a;
    alert(a); // that's why `a` is defined here 
    a=10;
    
    0 讨论(0)
  • 2020-11-29 04:03

    undefined: Declared but the value not asigned above where we access it in othe word it exist but the value not asigned

    'not defined': It is an error which indicate to the coder/programmer/user the variable doesn't exist in the scope. Not declare in scope.

    var a = 1;
    console.log(a) //1
    
    var b;
    console.log(b) //undefined
    
    console.log(c) //undefined
    var c=2;
    
    console.log(d) //undefined
    var d;
    
    e=3
    console.log(e) //3
    var e;
    
    console.log(f) //Uncaught ReferenceError: f is not defined
    
    > Note: the default behavior of javaScript moving declarations to the
    > top
    >So the above code is look like below internally
    
    var a = 1, b, c, d, e;
    console.log(a) //1
    
    console.log(b) //undefined
    
    console.log(c) //undefined
    c=2;
    
    console.log(d) //undefined
    
    e=3
    console.log(e) //3
    
    console.log(f) //Uncaught ReferenceError: f is not defined
    
    0 讨论(0)
提交回复
热议问题