The fact that in func2 you have globalVar = 5; and not var|let|const globalVar = 5; causes JavaScript to treat globalVar as a global variable. However, since you do not call func1, when globalVar is seen in func2 it is indeed still undefined.
If you add a call to func1 before calling func2, then by the time console.log is executed globalVar will be defined. Although if you are in strict mode, you will get an error complaining about trying to assign a value to an undefined variable (in func1). So, you'd better have a `var globalVar;' at the very top.
So, in essence
- if you have an assignment inside a function and the variable is not preceded with a
var|let|const qualifier it is assumed to be a variable defined in the global scope,
- if the variable is defined in the global scope all is good; if it is not, if you are in strict mode (if your code begins with
"use strict";), then there will be an error. If you are not in strict mode the variable will be defined in the global scope and execution continues.
fun1()to assign to the global.