Language: EN

ambito-de-variables-en-javascript

Variable Scope in JavaScript

In JavaScript, the scope of variables is a concept that refers to the part of the program where the variable is accessible.

JavaScript uses three types of scope:

  • Global scope
  • Local scope
  • Block scope

Global Scope

Global scope is the broadest context in which JavaScript code runs. Variables declared in the global scope are available anywhere in the code (including functions and blocks).

let globalVar = 'I am a global variable';

function showGlobal() {
    console.log(globalVar); // Accessible here
}

showGlobal(); // Prints: I am a global variable
console.log(globalVar); // Also accessible here

In the example above, globalVar is accessible both inside the showGlobal function and outside of it, because it is in the global scope.

It is advisable to use the fewest number of global variables, because in the long run they become a maintenance mess.


Local Scope

Local scope refers to variables declared within a function. These variables are only accessible within the function where they were declared.

function myFunction() {
    let localVar = 'I am a local variable';
    console.log(localVar); // Accessible here
}

myFunction(); // Prints: I am a local variable
console.log(localVar); // Error: localVar is not defined

In this case, localVar is only available inside myFunction. Trying to access localVar outside the function results in an error, as it is not in the global scope.

Block Scope

Block scope was introduced with ES6 and allows variables to be declared inside a block {}.

Variables declared with let or const have block scope, meaning they are accessible only within the block they are in.

function blockExample() {
    if (true) {
        let blockVar = 'I am a block variable';
        console.log(blockVar); // Accessible here
    }
    console.log(blockVar); // Error: blockVar is not defined
}

blockExample();

In this example, blockVar is only available within the if block. Attempting to access blockVar outside the block results in an error.