I will give you a long answer for a better explanation.
When the javascript engine cannot find a specific variable in memory, it will throw an error. More precisely, when the javascript engine ( execution context ) cannot "refer" to a variable in memory, it will throw a ReferenceError . This is not exactly the same as an ad error , at least in JavaScript.
There is a difference between a not defined error and an undefined value.
So do
var a = undefined;
and
var a;
both will register the same result, i.e. undefined . This is because when you just do var a; The javascript mechanism allocates memory for a variable and automatically sets it to undefined , which is different from reporting that a does not exist at all - in this case it will throw a ReferenceError .
Lifting
console.log(a); // undefined var a = 'something';
will register undefined because the javascript engine knows that a variable declared somewhere in the code means that the javascript engine actually does something before it executes the code - one of the things it does is raise the variables . Simply put, the code above is the same as
var a; // hoisted (declared and defined the value 'undefined') console.log(a); // undefined a = 'something' // update the defined value to 'something'
So yes, the declaration and definition occur together in javascript (automatically - if you yourself do not), and the default value is not undefined .
ES6
Just an extra note.
const a;
SyntaxError where an initializer (definition) is needed. const is the only time you need to declare and define manually.
kaizer1v
source share