Skip to main content
Mohammad Shehadeh — home (MSH monogram, letter M filled with the Palestinian flag)

Scope in JavaScript

Published on
Last updated on
2 min read

Scope is where values and expressions are available for use. Think of scopes as a pyramid: child scopes can access 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 move to the top of their containing scope during compilation. So they can be used before they appear in the code.

Because of hoisting, blocks scope let and const but not var. Declare a variable with var inside a block and it's hoisted to the containing function or global scope, not the block.

This is a key reason modern JavaScript prefers 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

Quick Recap

  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

Related Articles

GET IN TOUCH

Let's work together

I build fast, accessible, and delightful digital experiences for the web. Whether you have a project in mind or just want to connect, I'd love to hear from you.

Get in touch

or reach out directly at hello@mohammadshehadeh.com