An example of the difference between undefined and not defined in javascript


According to the research, there is a big difference between the two Test OS: ubuntu Test browser: chrome

Test case 1 The console. The log (a) ReferenceError: a is not defined

Test case 2 Var a, The console. The log (a) No error, but output undefined

Test case 2 Var b = {}; The console. The log (b.a) No error, but output undefined

Test case 3 The function c () { } Var d = new c(); The console. The log (da) No error, but undefined About the typeof All of the above objects that are being tested are returned with typeof as String(“undefined”) B sub b sub 0, b sub b sub 1 Var d = a | | 3 A not defined Var a; Var d is equal to a |, | 3 Results: d = = 3 Var c is equal to 22 times | times | 44 C = = 22 Var c = false || 33 C = = 33 If (x) { } An error Var x If (x) { } If not executed inside

Conclusion: There are two types of undefined in js even though the typeof returns a String(“undefined”) Once defined, but without any operations or an undefined property of an object, it is undefined, which can be used as a logical operation The second typeof variable, which is completely undefined and has no background (x. a. although x has no a attribute, but gives x face), is an error type and cannot be used except with the typeof function The or operation in js does not return the bool value, but returns the value that js calculated for the last condition on both sides, such as 1||2 1 is true, 2 does not need to calculate, so 1||2 == 1 a||1 error report Var a; A | | 1 = = 1;

Found a dictionary to translate Undefined means that you don’t know what to do with it And not defined can be translated to undefined