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
?
CodePudding user response:
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;
CodePudding user response:
Functions don't try to access variables until they are called, which happens after the a
variable has had a value assigned to it.
CodePudding user response:
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
CodePudding user response:
If we go line by line, we save the function sayHi
but do not call it. It is simply saved in the global memory as a function called sayHi
with the instructions of the functions inside of it.
We then save the variable a
as 1
in global memory.
Then we actually call the function sayHi
, running the inner block of code.
For the result
variable, JavaScipt will look into the local memory for name
and find it as "Alex"
as the argument for the name parameter. We then go to a
in which JavaScipt does the same thing and will look into the local memory, it won't find it. It then goes to global memory in which it will find it as the number 1
.
We can then successfully console the result, being "HiAlex1"
and end our code.
Hope that helps!