JavaScript:JavaScript Variables: let, const, and var Explained
JavaScript•Variables

JavaScript Variables: let, const, and var Explained

Modern JavaScript (ES6+) favors const for immutable bindings and let for reassignable variables, avoiding legacy var.

Syntax

const constantVal = "fixed"; let variableVal = 10;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
constDeclaration KeywordCreates block-scoped constants that cannot be reassigned.
letDeclaration KeywordCreates block-scoped reassignable variables.
varLegacy KeywordFunction-scoped variable with hoisting (avoid in modern JS).

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Modern JavaScript Variable Declarations
const appName = "Compilra";
const version = 3.2;
let activeUsers = 1420;
let isMaintenanceMode = false;

// Reassigning a let variable
activeUsers += 15;

console.log("App:", appName, "v" + version);
console.log("Active Users:", activeUsers);
console.log("Maintenance:", isMaintenanceMode);
Expected Output:
App: Compilra v3.2
Active Users: 1435
Maintenance: false

How It Works: Step-by-Step

  • Lines 2-3: Declares constant identifiers that cannot be reassigned.
  • Lines 4-5: Declares mutable state variables with let.
  • Line 8: Reassigns activeUsers using the += operator.

Key Concepts

  • Prefer const by default for all variable declarations.
  • Use let only when you know the variable value will be reassigned.
  • const prevents reassignment, but mutable objects bound to const can still have properties updated.

Common Mistake: Attempting to reassign a const variable

Reassigning a const variable throws a TypeError: Assignment to constant variable.

❌ Incorrect
const PI = 3.14;
PI = 3.14159; // TypeError!
✅ Correct
let PI = 3.14;
PI = 3.14159; // Valid with let

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler