MSH

Scope in JavaScript

Published on
Last updated on

The scope is where values and expressions are available for use. Scopes can be treated as a pyramid where child scopes have access to parent scopes.

JavaScript has 3 types of scope:

  • Global scope
  • Function scope
  • Block scope

Global Scope

The scope that contains and is accessible in all other scopes

1const someVar = 'declared in the global scope'; 2 3function someFunction() { 4 console.log(someVar); // accessible inside the function scope 5} 6 7someFunction();

Function Scope

The scope created with a function

1function someFunction() { 2 const someVar = 'declared inside a function'; 3 console.log(someVar); 4} 5 6someFunction(); 7 8console.log(someVar); // Reference error, (accessible only inside the function scope)

Variables created inside a function scope cannot be accessed from outside the function

Block Scope

The scope created with a pair of curly braces

1function someFunction() { 2 const someVar = 'declared inside a function'; 3 4 if (someVar) { 5 const someVar2 = 'declared inside a block'; 6 } 7 8 console.log(someVar2); // Reference error (accessible only inside the block scope) 9} 10 11someFunction();

Variables created inside a block scope cannot be accessed from outside the block

Hoisting

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation. This means they can be used before they appear in the code.

Blocks only scope let and const declarations, but not var declarations due to hoisting. When you declare a variable with var inside a block, it's actually hoisted to the function or global scope that contains it, not the block scope.

This is one of the key reasons why modern JavaScript recommends using let and const over var.

1{ 2 var someVar = 1; 3} 4 5console.log(someVar); // 1 6 7{ 8 const someVar = 1; 9} 10 11console.log(someVar); // ReferenceError: someVar is not defined

Key Takeaways

  1. Scope Types

    • Global scope: Accessible everywhere
    • Function scope: Limited to function boundaries
    • Block scope: Limited to block boundaries
  2. Variable Declaration

    • var declarations are function-scoped
    • let and const are block-scoped
    • Block scope only affects let and const
    • var declarations are affected by hoisting
  3. Best Practices

    • Use const by default
    • Use let when reassignment is needed
    • Avoid var in modern JavaScript
    • Be mindful of scope boundaries

References

GET IN TOUCH

Let's work together

I build exceptional and accessible digital experiences for the web

WRITE AN EMAIL

or reach out directly at hello@mohammadshehadeh.com