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

The global scope is the broadest context in which the JavaScript code is executed. 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 previous example, 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 global variables possible, because they can become a maintainability mess in the long run.


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 within myFunction. Trying to access localVar outside of 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 within 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. Trying to access blockVar outside the block results in an error.