Tobias Rauer - Web Software & Security Engineer
RAWr co.detheme

Scope & Hoisting in Javascript

Published on Mon, 13 Feb 2023 by Tobias Rauer

Table of Content

Function Scope vs Block Scope

Function Scope

Scoping refers to the visibility and accessibility of variables within the code. Variables declared with the var keyword have function scope, meaning they are only accessible within the function they were declared in. Variables declared with let and const have block scope, meaning they are only accessible within the block they were declared in.

The var, let, and const keywords in JavaScript are used to declare variables, and they behave differently in terms of scope and value assignment.

var is function scoped, meaning that a variable declared with var is accessible within the entire function in which it is declared, as well as any nested functions. If a var variable is declared within a block, it is still accessible outside of the block. For example:

function example() {  
	if (true) {     
		var functionScope = 'I am function scoped';   
	}
	
console.log(functionScope); // Output: I am function scoped 
}

In this example, the functionScope variable is declared with var and is accessible outside of the if block.

Block Scope

let and const are block scoped, meaning that a variable declared with let or const is only accessible within the block in which it is declared, as well as any nested blocks. For example:

function example() {   
	if (true) {     
		let blockScope = 'I am block scoped';   
}    

console.log(blockScope); // Uncaught ReferenceError: blockScope is not defined
}

In this example, the blockScope variable is declared with let and is not accessible outside of the if block.

Hoisting

Hoisting refers to the behavior of variables and function declarations being moved to the top of the current scope during the execution of the code ("hoisted"). For example:

console.log(hoistedVar); // Output: undefined
var hoistedVar = 'This is a hoisted variable';  

console.log(hoistedFunc()); // Output: 'This is a hoisted function'
function hoistedFunc() {
	return 'This is a hoisted function';
}

In the example above, the declaration of hoistedVar and hoistedFunc are hoisted to the top of the scope, meaning they can be accessed before they are declared in the code. However, their initialization remains in the same place and is not hoisted.

Understanding scope and hoisting is important in writing efficient and maintainable code, as it affects the accessibility and behavior of variables and functions within your code.

Javascript