JavaScript(JS) Variable Scope
JavaScript has two types of variable scope: global and local.
A global variable is one that is defined outside of any function and can be accessed from anywhere in the code. A local variable, on the other hand, is one that is defined inside a function and can only be accessed within that function.
Here is an example of a global variable:
let globalVariable = "Hello, world!"; function greet() { console.log(globalVariable); } greet(); // Output: "Hello, world!"Souww:ecrw.theitroad.com
In this example, the variable globalVariable
is defined outside of any function and can be accessed from within the greet
function.
Here is an example of a local variable:
function greet() { let localVariable = "Hello, world!"; console.log(localVariable); } greet(); // Output: "Hello, world!" console.log(localVariable); // Throws a ReferenceError
In this example, the variable localVariable
is defined inside the greet
function and can only be accessed from within that function. Trying to access localVariable
from outside the function will result in a ReferenceError
.
It's important to note that variables declared with var
keyword have function scope, which means they are only accessible within the function where they are declared. However, variables declared with let
or const
have block scope, which means they are only accessible within the block where they are declared (including inside any nested blocks).
Here is an example:
function test() { var x = 1; let y = 2; const z = 3; if (true) { var x = 4; let y = 5; const z = 6; console.log(x, y, z); // Output: 4, 5, 6 } console.log(x, y, z); // Output: 4, 2, 3 } test();
In this example, the var
variable x
is accessible both inside and outside of the if
block because it has function scope. However, the let
variable y
and the const
variable z
are only accessible within their respective blocks.