SKIP TO MAIN
This site has been archived. Please visit my new website at mohammadshehadeh.com

Scope in JavaScript

June 20, 2024

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

const someVar = "declared in the global scope";
 
function someFunction() {
	console.log(someVar); // accessible inside the function scope
}
 
someFunction();

Function Scope#

The scope created with a function

function someFunction() {
	const someVar = "declared inside a function";
	console.log(someVar);
}
 
someFunction();
 
console.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

function someFunction() {
	const someVar = "declared inside a function";
 
	if (someVar) {
		const someVar2 = 'declared inside a block';
	}
 
	console.log(someVar2); // Reference error (accessible only inside the block scope)
}
 
someFunction();

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

Blocks only scope let and const declarations, but not var declarations due to hoisting.

{
	var someVar = 1;
}
 
console.log(someVar); // 1
 
{
	const someVar = 1;
}
 
console.log(someVar); // ReferenceError: someVar is not defined

References#

GET IN TOUCH

Let’s work together

I build exceptional and accessible digital experiences for the web

WRITE AN EMAIL