The difference is that undefined
refers to the value of the variable and is not defined
is an error message indicating that the variable does not exist in the program that is running.
a; // undefined (indefinido)
The variable is declared in the script, but has no value assigned. No value was set, so its value is rejected.
Notice that this can happen in different ways:
var a;
console.log(a); // undefined
but also:
console.log(a); // undefined
var a;
and this last case is not equal to the problem of b
because somewhere in the script the variable is declared. This is no longer possible (and still good) with let
or const
, then it would be a mistake:
Cannot access 'a' before initialization
b; // ReferenceError: b is not defined
Actually today in modern Javascript (if it didn’t exist var
) it would be more correct to say is not declared
or is not initialised
because it may be declared but have no value assigned.
In this case the variable b
is never declared so cannot be used. Even if you were on the bottom line b = 'foo';
That’s not the same as var b = 'foo';
and so the variable is never initialized.
typeof a|b
The case of typeof
is different because one of the characteristics of typeof
is able to scan the value of the operand even if it is not declared/initialized.
I’ll disagree a little bit with you :D... "empty" is a definite value. Therefore, "Undefined" is something that has not been defined, so it has no value, not even "empty".
– Sam
Just to complement, this would be empty
var a = '';
and that would be "Undefined":var a;
. So emptiness has nothing to do with Undefined.– Sam
Difference between "empty" and
null
/undefined
: https://i.stack.Imgur.com/j9vg8.jpg– hkotsubo