JavaScript var keyword

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?

Hello Nibble.

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.

You are accessing an identifier (variable name) that do not yet exist. It is declared and assigned when the function runs, not when it is defined.

myNumber()
console.log(num) // 10
function myNumber() {
  num = 10;
  return num
}

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)

1 Like

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.