Var and Hoisting

My First Question: javascript takes declarations and put on the top of function code because of hoisting before any code executed, i want to know that in this situation which i stated below there is two variables declared they are written like this var a, a;? because of hoisting on the top of function code ? if like that why i am not accessing second variable a before initilization why i am accessing first variable a after initilization, In short on line 4 of function code console.log(a) // 10 how javascript decide to give 10 and not undefined, Note that there is two variables declare with same name on top.
My Second Question: it is possible when javascript scan the code and find 2 variables with same name and it remove one variable and used another in the code execution.
function myFunc() {
var a = 10;
var a = 20;

1 Like

Welcome back, @Junaid_Arshad :wave:

It’s not possible to have two variables with the same name. The second a in var a, a; is just a redeclaration of the first a (it does nothing). So there is just one variable a that is first undefined (because of hoisting), then initialized with 10 and finally updated to 20.

Since redeclarations often happen by accident it’s preferred to use let instead of var. let will throw a syntax error if you try to redeclare the variable.

I hope my explanation is understandable. Feel free to ask more questions :blush:

Happy coding,


Thanks friend it is a fantastic answer

1 Like