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:
| Parameter | Type | Description |
|---|---|---|
| const | Declaration Keyword | Creates block-scoped constants that cannot be reassigned. |
| let | Declaration Keyword | Creates block-scoped reassignable variables. |
| var | Legacy Keyword | Function-scoped variable with hoisting (avoid in modern JS). |
Ready-to-Run Code Example
Executable in CompilraRun 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
JavaScript Operators: Arithmetic, Comparison & Strict Equality
Explore arithmetic, comparison, logical, and nullish coalescing (??) operators in JavaScript.
JavaScript Console I/O: Logging, Tables, and Formatting
Master console output with console.log, console.table, and standard process streams.
JavaScript Type Conversion and Coercion with Examples
Learn explicit vs implicit type conversion in JavaScript using Number(), String(), and Boolean().
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.