Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Scope

Scope is the part of a program where a variable exists and can be reached by its name. Thanks to scope, the variables of one function do not interfere with another, even when they share names.

Local variables

A variable declared inside a function is called local. It is created when the function is called and disappears when the function finishes:

function calculate() {
  const result = 2 * 21;
  return result;
}
 
console.log(calculate()); // 42

Outside the function the variable result does not exist. The typeof operator returns 'undefined' for an unknown name, so this is easy to check:

function calculate() {
  const result = 42;
  return result;
}
 
console.log(typeof result); // undefined

Global variables

A variable declared outside all functions and blocks is called global. Every function in the program can see it:

const currency = '$';
 
function formatPrice(amount) {
  return `${currency}${amount}`;
}
 
console.log(formatPrice(15)); // $15

Global variables are handy for settings, but do not overuse them: if different functions change them, it is hard to tell where a value came from.

Blocks limit visibility too

Variables declared with let and const are visible only inside the curly-brace block where they are declared: an if, a loop or a function. This is called block scope:

const age = 20;
 
if (age >= 18) {
  const message = 'Access granted';
  console.log(message); // Access granted
}

After the closing brace, message no longer exists. The counter of a for (let i = 0; ...) loop behaves the same way — it does not exist outside the loop.

Inner code sees outer variables

Scopes are nested inside each other. Code inside a block or function sees its own variables and all the outer ones, while outer code cannot see the inner ones:

const greeting = 'Hello';
 
function greet(name) {
  const text = `${greeting}, ${name}!`;
  return text;
}
 
console.log(greet('Anna')); // Hello, Anna!

The greet function uses its own parameter name, its own variable text and the outer greeting.

Shadowing

If a function declares a variable with the same name as one outside, the inner one shadows the outer one: inside the function only the inner variable is visible. The outer variable is not changed:

const name = 'Anna';
 
function show() {
  const name = 'Oleg';
  return name;
}
 
console.log(show()); // Oleg
console.log(name);   // Anna

Shadowing is easy to do by accident, so it is better to give variables different names.

Common mistake

A variable declared inside a block is used after the block. The program stops with an error:

if (true) {
  const total = 100;
}
 
total; // ReferenceError: total is not defined

If you need the value after the block, declare the variable before it with let and only assign inside the block: let total; and then total = 100;.

Thanks for reading!

Donate to the site — we work hard for you.