I will give you a long answer for better explanation.
When the javascript engine is not able to find a particular variable in memory, it will throw an error. To be more specific, when the javascript engine (Execution Context) is not able to "reference" a variable in memory, it will throw a ReferenceError
. This is not exactly the same as a Declaration Error, at least in javascript.
There is a deference between a not defined
error and the value undefined
.
So doing
var a = undefined;
and
var a;
will both log the same result i.e. undefined
. This is because, when you simply do a var a;
the javascript engine allocates memory for the variable and automatically sets it's value to undefined
, which is different from saying that a
doesn't exist at all - in which case it will throw a ReferenceError
.
Hoisting
console.log(a); // undefined
var a = 'something';
will log undefined
because, the javascript engine knows there's a variable declared somewhere in the code - which means to say that the javascript engine actually does something before it executes the code - one of the thing it does is hoists variables. To put it simply, the above code 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, declaration and definition happen together in javascript (automatically - if you don't do it yourself) and the default defined value is undefined
.
ES6
Just an additional note
const a;
will throw a SyntaxError
where a initializer (definition) is necessary. const
is the only time when you need to declare and define manually.