Quiz

Explain the difference between global scope, function scope, and block scope

Topics
JavaScript

TL;DR

Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within {}) they are declared in.

var globalVar = "I'm global"; // Global scope
function myFunction() {
var functionVar = "I'm in a function"; // Function scope
if (true) {
let blockVar = "I'm in a block"; // Block scope
console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
}
// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined
myFunction();

Nested scope boundaries

Inner scopes can read bindings from their enclosing scopes, but outer scopes cannot read bindings declared only inside an inner function or block.

Global, function, and block scope nesting

var ignores ordinary block boundaries but remains scoped to its containing function; let, const, and class declarations are block-scoped.

Global scope, function scope, and block scope

Global scope

Variables declared in the global scope are accessible from anywhere in the code. In a browser environment, these variables become properties of the window object.

var globalVar = "I'm global";
function checkGlobal() {
console.log(globalVar); // Accessible here
}
checkGlobal(); // Output: "I'm global"
console.log(globalVar); // Output: "I'm global"

Function scope

Variables declared within a function are only accessible within that function. This is true for variables declared using var, let, or const.

function myFunction() {
var functionVar = "I'm in a function";
console.log(functionVar); // Accessible here
}
myFunction(); // Output: "I'm in a function"
// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined

Block scope

Variables declared with let or const within a block (e.g., within {}) are only accessible within that block. This is not true for var, which is function-scoped.

if (true) {
let blockVar = "I'm in a block";
console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
if (true) {
var blockVarVar = "I'm in a block but declared with var";
console.log(blockVarVar); // Accessible here
}
console.log(blockVarVar); // Output: "I'm in a block but declared with var"

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise 1 of 2
Check your understanding Exercise 1 of 2

What does this code log?

const value = 'global';
function inspect() {
let value = 'function';
if (true) {
let value = 'block';
var visible = 'var';
}
return `${value}:${visible}`;
}
console.log(`${inspect()}:${value}`);