I have some lines of code : why print 'undefined' and 'B' on my browser . Can you explain for me?
var x = 'A';
function func(){
document.write(x);
var x = "B";
document.write(x);
};
func();
I have some lines of code : why print 'undefined' and 'B' on my browser . Can you explain for me?
var x = 'A';
function func(){
document.write(x);
var x = "B";
document.write(x);
};
func();
It's JavaScript Hoisting. In your example x
inside that function is hoisted. In JavaScript, variable declarations are only hoisted, NOT their initializations.
Update:
Regarding ES6, const
and let
declarations are not hoisted.