JavaScript Variables and Constants

Dive into JavaScript variables and constants

October 9, 2024

What is a variable?

A variable is a storage location that can hold a value. It can be changed during the execution.

In JavaScript, we can declare a variable using var, let, or const. In modern JavaScript, using let and const to declare a variable is the preferred option.

var age = 23;
age = 24;
 
let height = 1.59;
height = 1.62;

What is a constants?

Like a variable, but the value cannot be changed once it is assigned.

const PI = 3.14;
PI = 3.14159; // This will throw an error

Key Differences:

Scoped

Let and Const Declarations

let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.

Variable Statement

A var statement declares variables that are scoped to the running execution context's VariableEnvironment.

LexicalEnvironment

// Block-scoped
function greeting() {
  ...
};
 
if(true) {
...
} else {
...
};
 
for(...) {
...
}

VariableEnvironment

Key differences between LexicalEnvironment and VariableEnvironment

Let’s practice and review the concepts that we’ve mentioned in this article.

function testScope() {
  var a = 1;
  let b = 2;
  const c = 3;
 
  if (true) {
    var a = 4;
    let b = 5;
    const c = 6;
    console.log(a); // ?
    console.log(b); // ?
    console.log(c); // ?
  }
 
  console.log(a); // ?
  console.log(b); // ?
  console.log(c); // ?
}
 
testScope();

Answer

function testScope() {
  var a = 1;
  let b = 2;
  const c = 3;
 
  if (true) {
    var a = 4;
    let b = 5;
    const c = 6;
    console.log(a); // 4
    console.log(b); // 5
    console.log(c); // 6
  }
 
  console.log(a); // 4
  console.log(b); // 2
  console.log(c); // 3
}
 
testScope();

Explanation

Inside this testScope function, variable a has been modified from 1 to 4 inside the if statement. That's why when we console.log(a), the answer was 4 instead of 1, because a was managed by the VariableEnvironment and it lived in the whole function scope.

Think of when we use var to declare a variable, it has the access to enter every room (function scope and block scope).

On the other hand, using let and const to declare variables means they are managed by the LexicalEnvironment. We can think of this as having two rooms: the first set of b and c lives in the room of the function scope, and the second set of b and c lives in the room of the if statement (block scope).

Therefore, when we console.log(b) and console.log(c) within the if block, the values were 5 and 6, because it could only access the values within the if statement. When we try to console.log(b) and console.log(c) outside of the if statement, it can access the values within the function scope but cannot access the values that lived inside the if statement.

Back to Blog 🏃🏽‍♀️