Dear Campers,
According to W3 any variable declared without var keyword in a function definition becomes a global variable. This means the variable is even accessible outside the function. However when I define myNumber:
function myNumber(){
num = 10
return num
}
However when I try to access the now supposed global variable num before the function declaration, I get an error.
console.log(num) // Error
function myNumber(){
num = 10
return num
}
console.log(myNumber())
But when I try to access the variable after function declaration, I don’t get an error.
function myNumber(){
num = 10
return num
}
console.log(myNumber())
console.log(num)
If indeed var becomes a global variable, in the function declaration, why do I get an error when trying to access it before function declaration?
Is it because the function definition is executed after function invocation?
It is summed up pretty much in the last section of w3schools:
The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
In a web browser, global variables are deleted when you close the browser window (or tab).
Perhaps it could work slightly differently with different compilers, but I am not sure.
The code is evaluated top to bottom. The variable doesn’t exist until you declare it. Global variables do get hoisted, but only to the top of the scope they are declared in, which in this case is the function myNumber.
(Note that in a standard modern real-life setup that uses strict mode, this code will just flat out refuse to work because you’re attempting to assign to an undeclared variable)
Thanks for the answer. I also suspected so because a function definition is not executed until the function is invoked. Therefore, even if the function definition is hoisted to the top of the current execution context, the num variable is not created until it’s block of code is executed.