DEV Community

Holden Gerner
Holden Gerner

Posted on

JavaScript Scope

What is Scope?

  • Scope determines the accessibility of variables

  • JavaScript has 3 different types of scope

    1. Block
    2. Function
    3. Global

Types of Scopes

  • Block Scope:
    A variable that is defined within a block of code will only be accessible within that block. It can not used outside the block even if the block is inside a function.

  • Function Scope:
    A variable that is defined in a function can only be used within that function. The variable can be used within a block that is inside that function, but cannot be used outside of the function itself.

  • Global Scope:
    A variable that is defined as a global variable is accessible to the entire program. Meaning that a function can access this function as well as the block inside that function.

Image description

Example of Scope

const name = "Holden"
const age = 22

function checkMyAge(name, age){
   const word = "You are"
   if(age < 21){
     const oldEnough = "old enough."
     console.log(`${name}, ${word}${age} and are ${oldEnough}`)
   }
   else{
     const notOldEnough = "not old enough."   
     console.log(`${name}, ${word} ${age} and are ${notOldEnough}`)
   }
}
checkMyAge(name, age)
Enter fullscreen mode Exit fullscreen mode

As you can see the variables name and age are global scope variables. The variable word is a function scope variable which means it can only be accessed inside the checkMyAge function. The variables oldEnough and notOldEnough are block variables which can only be accessed inside the if and else statements respectfully. Since the age variable is 22, the function's output should be "Holden, you are 22 and are enough."

Recap

Scope is an extremely used aspect in JavaScript. It manages the availability of variables within a program. It keeps those variables confined into separate parts of your code. You may use the name of these variables in multiple parts of your code and scope allows you to use them when needed.

Sources

Top comments (0)