A variable is still in scope inside any nested braces within its own scope. It's only trying to access a variable outside its scope that causes an error.
Top-level scope
A variable declared at the "top level" of a script file, i.e. not inside any braces, as with message in the previous example, is scoped to that entire file. If you add another script file, the variable won't be accessible there as other files are outside the scope of a top-level variable.
Note that top-level scope can work differently in other JavaScript environments. Construct uses modern "module" scripts, where top-level scope works this way. However if other tools or environments use the older "classic" scripts, top-level scope is actually global scope, and so top-level variables can be used across different files. Despite the fact this does not happen in Construct, it's still common in the rest of the industry, so it's worth being aware that this can work differently elsewhere.
Functions have scope too
Functions are also scoped to the place they are declared. Again referring to the previous example, the logMessage function is declared at the top level, and so can be used anywhere inside that script file, but not in other script files.
To demonstrate the scope of functions, try this code sample:
function logMessageOuter()
{
function logMessageInner()
{
console.log("Hello world!");
}
logMessageInner();
}
// 'logMessageInner' is not accessible here
logMessageOuter();
This declares a nested function, or a function inside another function. logMessageInner can only be used in the function logMessageOuter and not outside of it. The function is scoped the same way as a variable declared inside logMessageOuter.
Summary
Scope is an important aspect of variable declarations, function declarations and function parameters, which defines where they can be used. In short, each pair of braces {
and }
defines a new scope, and anything not inside any braces is at the top level. Something declared in a particular scope can be used anywhere inside that scope, including inner scopes, but not outside of that scope. Scope becomes an important feature when dealing with functions, which is why we took a little detour to cover it now.
These rules about scope help keep code organised as it prevents things being accidentally used outside of where they're meant to be used. It also generally removes the need to worry about if a name is used somewhere else in a large program, since you only need to think about what is in scope for a particular piece of code.
It is possible to use top-level functions and variables in other script files if they are explicitly placed in global scope, or exported and imported, but these are more advanced topics that we'll cover later on in this guide.