Skip to main content

In general, the concept of scope in computer programming pertains to the accessibility of variables and functions from a given point of the code. In other words, as you write a line of code, what variables and functions do you have access to?

If a line of code doesn't have access to a variable/function, we could say that variable/function is "out of scope".

Types of Scope in Javascript

  1. Global Scope
  2. Local (Function Scope or Block Scope)

We touched on this briefly in Variables notes but let's go through it in more detail.

But first why do we have different types of scope?

One of the keys of this principle is based on the idea that limiting the accessibility of variables (and functions) helps reduce bugs in the code - think of it as a form of "code safety".

scope example
// global scope ✨
var x = 10;
var y = 'Hello';

function exampleFunction() {
// function scope ✨
var z = 5;
}

// block scope ✨
if (true) {
var x = 10;
console.log(x); // 10
}

console.log(x); // 10

Global Scope

Variables declared outside any function or block are in the global scope. They can be accessed from anywhere in your code.

// global scope ✨
var x = 10;

console.log(x);

Local Scope

Variables declared inside a function or block are in the local scope. They are only accessible within that specific function or block.

Function Scope
function exampleFunction() {
// function scope ✨
var z = 5;
}
Block Scope
// block scope ✨
if (true) {
var x = 10;
console.log(x); // 10
}

console.log(x); // 10

Hoisting for Functions!

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase.

This means that no matter where you declare a variable or a function in your code, JavaScript will move it to the top before it's actually executed.

So this actually works!:

console.log(sayHello());

function sayHello() {
return 'hello';
}

Eventhough my function was declared after my console.log, no error was thrown and it worked!

However, this (arrow functions) will not work:

console.log(sayHello());

const sayHello = () => {
return 'hello';
};

Do you remember about hoisting in variables. It's important to note for variables that only the declarations are hoisted, not the initializations (the actual assignments).

This can lead to a subtle behavior where you can use a variable before it's assigned a value, which results in the variable having an "undefined" value.

console.log(a); // undefined
var a = 10;

In summary:

  • var: only declaration hoisted and processed
  • functions: fully hoisted