In JavaScript, an undeclared variable is a variable that has not been declared using the var
, let
, or const
keywords. An undefined variable is a variable that has been declared, but has not been assigned a value.
For example:
javascript// Undeclared variable
x = 10;
console.log(x); // 10
// Undefined variable
var y;
console.log(y); // undefined
In the above code, x
is an undeclared variable because it is not declared using any of the keywords (var
, let
, or const
). JavaScript automatically creates a global variable with the name x
and assigns the value 10
to it. On the other hand, y
is a declared variable, but it has not been assigned any value. Therefore, it has the value undefined
.