In this JavaScript documentation, it says:
var statements and function declarations at the top level create properties of the global object. On the other hand, let and const declarations never create properties of the global object.
What does "function declarations at the top level" mean? does it mean functions that are not inner functions?
Top level means not inside other functions or objects or classes or closures. Where this
refers to the window
object.
console.log(this === window) // true
var x = 5
function foo() {
console.log(this === window) // true
var y = 3
}
foo.call(this);
console.log(y) // not defined
What does "function declarations at the top level" mean? Does it mean functions that are not inner functions?
Yes, it means just that. It refers to the syntax of the declarations: anything that is not nested inside some other syntactical structure.
However, the statement is not quite accurate. It should be restricted to the "top level of scripts", since var
and function
declarations at the top level of module code don't create global variables - they declare variables in the global scope. Also, var
declarations in blocks ({ … }
) still declare global variables (that become properties of the global object) as long as they're not nested in a function.