Reputation: 305
In Javascript how does variable used before definitions?
console.log("b ", b);
var b;
I want to understand how above statement work in javascript?
Upvotes: 1
Views: 1648
Reputation: 7591
You can use d and then initialize d it will print undefined.
but if you use d with out any initialization it will return b is not defined Error .
console.log("d",d);
console.log("b "+b);
var b = "What do you mean ?"
console.log("b ",b);
Upvotes: 0
Reputation: 1
b
is undefined
at code at Question. However, if b
were a function, that variable declaration would be "hoisted" see 'Hoisted' JavaScript Variables and b
would be defined within console.log()
even where not actually defined until the next line.
console.log("b ", b);
function b() {}
Upvotes: 2
Reputation: 34914
JS first check how many variable and functions are going to use and variable are assigned as undefined and assigned at last.
So in the first example you can understand like var b = undefined
and then console.log("b ", b);
and then b=1
;
console.log("b ", b);
var b=1;
console.log("b ", b);
var b=1;
console.log("b ", b);
Upvotes: 1