Variable scope in functions
In this section, we will discuss a topic that is often considered challenging. We will talk about scope. Scope defines where you can access a certain variable. When a variable is in scope, you can access it. When a variable is out of scope, you cannot access the variable. We will discuss this for both local and global variables.
Local variables in functions
Local variables are only in scope within the function they are defined. This is true for let
variables and var
variables. There is a difference between them, which we will touch upon here as well. The function parameters (they do not use let
or var
) are also local variables. This might sound very vague, but the next code snippet will demonstrate what this means:
function testAvailability(x) {
console.log("Available here:", x);
}
testAvailability("Hi!");
console.log("Not available here:", x);
This will output:
Available here: Hi!
ReferenceError: x is...