DEV Community

Cover image for JavaScript Tutorial Series: Scope
The daily developer
The daily developer

Posted on • Updated on

JavaScript Tutorial Series: Scope

The concept of scoping is essential because it makes it easier to organize code and avoids naming conflicts.

What is a Scope?

A scope specifies how accessible variables and functions are within a block of code. It points out where a variable or function can be used and which portion of the code has access to it.

3 types of Scopes

Any statement enclosed in curly braces, such as a function, loop, or conditional statement, is considered a block of code.

Global Scope

The term "global scope" describes variables that are reachable from anywhere in the code. In other words, any variable declared outside of a function or block is in the global scope.

let x = "I'm a global variable";

function myFunction() {
  console.log(x); // output: I'm a global variable
}

myFunction();
console.log(x); // output: I'm a global variable
Enter fullscreen mode Exit fullscreen mode

Function Scope

The term "function scope" refers to variables that are only accessible within the function in which they are declared in. This means that variables declared inside of a function are not accessible outside of that function.

function myFunction() {
  let word = "I'm inside of a function";
  console.log(word); // output: I'm inside of a function
}

myFunction();
console.log(word); // Uncaught ReferenceError: word is not defined
Enter fullscreen mode Exit fullscreen mode

Block Scope

Variables declared inside a block can only be accessed from within that block and any nested blocks that are part of that block scope.

Naming conflicts can be avoided with other parts of the code by defining variables within a block scope, which makes the variable names only accessible within the block.


function myFunction() {
  let a = 5; //only accessible in myFunction
  if(a > 3) {
    let b = 12;
    //only accessible in this block of code
    console.log(b); 
  }
  console.log(a); //5
  //Uncaught ReferenceError: b is not defined
  console.log(b); 
}

myFunction();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)