This is called hoisting
in javascript.
(1)
console.log(a);
a = 1; // this will have a is not defined;
In the above snippet, a is assigned after console
, so it is throwing an error.
In case if you have
console.log(a);
var a = 1;
The result will be undefined
printed in the console. It is because of hoisting. Javascript will execute the above in the following order.
var a;
console.log(a);
a = 1;
Hoisting is executing the initialisation first and rest of the execution will go as per the flow.
var a;
is executed first and a
is initialized to the scope. Hence console.log(a)
will not throw any error. At the time of its execution, a
value is undefined
.
(2)
console.log(a);
a = 1;
window.a === 1; // true
Whenever you try to do anything in the console, all the variables and functions will be registered with the window
scope. So, when you do a = 1
in console, it will be window.a
.
(3)
console.log(a);
function a(){}; // this will have no error;
The same hoisting
applies to functions also. When you created a function using constructor like above, it will be hoisted
. If you execute the below snippet you will get error because it is not hoisted
.
console.log(a)
a = function(){}
why is the variable a bound to window but console.log still has an error.
The variable is registered with window
scope, but it is not hoisted. So you will get error. Hoisting
will only work when you initialize a variable.
To get further details about hoisting
, feel free to read docs