DEV Community

Cover image for Talking about Scopes
ccaldwell11
ccaldwell11

Posted on

Talking about Scopes

Scopes are a way to determine the accessibility and location of specific variables that may be located within a program. This becomes useful to many (if not all) programmers due to the assistance it provides when debugging code, increasing code efficiency, and significantly reducing the amount of variable [name] conflicts.

Global scope

The global scope refers to the scope that the entire program is able to access (hence the name global). Any variable declared outside of a function or code block is a global variable. Additionally, any value that has been assigned to variables that have not been defined & variables that begin with the 'var' keyword are also found in this scope.

// Global scope
var globalVar = "I am in the global scope";

function globalExample() {
  console.log("This is in the global scope");
}

globalExample();
console.log("This isn't in the global scope");
Enter fullscreen mode Exit fullscreen mode

Function scope

Each function that is created simultaneously creates a function scope. Variables declared inside of a function's curly brackets are considered 'function-scoped variables' and can only be accessed within that function it was declared in or any scope that encases the specific function. 'Let' and 'const' variable declarations can be found here.

function functionExample() {
  // Function-scoped
  let functionVar = "I am in the function scope";
  console.log("This is in the function scope");
}

functionExample();
// Attempting to access functionVar here would result in an error
console.log("This isn't in the function scope");
Enter fullscreen mode Exit fullscreen mode

Block scope

Block-scoped variables simply refer to any variable that has been declared within a 'block' (the contents between a set of curly brackets '{}'). Variables declared in this scope can only be accessed by parent scopes or from within the block scope itself. This feature was introduced in the ES6 update of JavaScript which was published in 2015.

function blockExample() {
    // Block scope
    let blockVar = "I am in the block scope";
    console.log("This is in the block scope");
    console.log(blockVar);
  }

  // blockVar cannot be accessed here due to it residing between curly brackets
  console.log("This isn't in the block scope");
}

blockExample();
Enter fullscreen mode Exit fullscreen mode

Scopes refer to the context in which a certain variable is defined and accessed. This becomes useful when variables share the same name or are being accessed incorrectly and those issues need to be resolved. With the logic of scopes, programmers can avoid bugs and unwanted variable manipulation as well.

Top comments (0)