Hoisting in Functions in Javascript
- Hoisting Javascript
- Functions are hoisted completely i.e, a function can be called before it is declared.
functionName(); // Chaitanya
function functionName() {
console.log("Chaitanya");
}
What will be the output of the following code?
var x = 21;
var fun = function () {
console.log(x);
var x = 20;
};
fun();
?
https://youtu.be/btwFJT_xzdg?t=755&si=V4wkk0Q37IwVnLV0
- Answer is
undefined, but why?var xis hoisted with the valueundefinedvar funa Function Expression Javascript is hoisted.xis initialized to21- Local
var xshadows the global x and hoisted with the values ofundefined console.log(x)is before initialization of x- Therefore the value
undefinedis printed