Mark As Completed Discussion

Understanding Variable Scope in JavaScript

In JavaScript, variable scope determines the accessibility of variables within a program. The scope of a variable defines where it can be accessed and where it is visible.

  • Global Scope: Variables declared outside of any function or block have global scope and can be accessed anywhere in the program.

    JAVASCRIPT
    1// Global variable
    2const name = 'John';
  • Local Scope: Variables declared within a function or block have local scope and can only be accessed within that function or block.

    JAVASCRIPT
    1function greet() {
    2  // Local variable
    3  const message = 'Hello';
    4  console.log(message + ', ' + name);
    5}

    When the greet() function is called, it can access the global variable name and the local variable message. However, variables defined within the function or block are not accessible outside.

    JAVASCRIPT
    1greet(); // Output: Hello, John
    2console.log(name); // Output: John
    3console.log(message); // Error: message is not defined
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment