In hoisting, do variables take precedence over function definition or the other way round? Please see the code below:
function a()
{
var x = 10;
function x() {
return 20;
}
return x;
}
In hoisting, do variables take precedence over function definition or the other way round? Please see the code below:
function a()
{
var x = 10;
function x() {
return 20;
}
return x;
}
It's not a matter of one taking precedence over the other (there is precedence taking place, but that's largely just a matter of semantics).
What matters here is that the assignment part of the variable declaration is not hoisted, whereas the entire function definition is.
Functions are hoisted before variable declarations, but the net effect is the same.
After hoisting, your function will act like this:
the
x = 10
takes place after all the hoisting is done, so that is the value that remains inx
.To respond to @thefourtheye's request (I think this is what s/he is asking for), if your original function looked like this:
Then after hoisting, it would look like this (same as above):
As one last illustration, try this:
When called, this prints out:
The reason for this is that hoisting is causing the function to behave like this: