What is VAR hosting in JavaScript ?

If you write a variable and assigned it before declare, like below example

a = 10
console.log(a+20)
var a

It will work perfectly.
Here, I have assigned a variable by value 10, and I also used this variable in console.log() , and it has given output 30.
This behavior is called “hoisting“. Where a variable can appear to be used before it’s declared.

In JavaScript new feature they has introduced LET . Now if you change var a  to let a . You will get an error. If we want to avoid var hosting we can write like below example.

let a
a = 10 
console.log(a+20)

Leave a Reply

Your email address will not be published. Required fields are marked *