function sayHi(name){
let result="Hi"+name+a;
console.log(result)
}
let a=1;
sayHi("Alex")
The result of the above code is Hi Alex1, so from what I understand is the variable a is hoisted, but in JS, only the declaration is hoisted, not the initialisation, so how come the result can use the value of a?
Because the value is set before the operation is called. Look at the order of these two things:
let a=1;
sayHi("Alex")
First the value of a is set to 1, then the function sayHi is invoked. Within that function the value of a is used.
Swap the two statements and see a different result:
function sayHi(name){
let result="Hi"+name+a;
console.log(result)
}
sayHi("Alex")
let a=1;
Functions don't try to access variables until they are called, which happens after the a variable has had a value assigned to it.
Javascript works like a waterfall.
This means code will be compiled from the higher level.
The variable a is initialized before the function sayHi is called:
so you have access to his value.
Check how scope works as well here https://www.w3schools.com/js/js_scope.asp