<htmlstart/>

JS Variables

Store and reuse values with var, let, and const.

Declaring Variables

JavaScript has three keywords for declaring variables:

const name = "Alice";   // constant — cannot be reassigned
let   age  = 25;        // block-scoped — can be reassigned
var   city = "London";  // function-scoped — avoid in modern JS

const vs let

constlet
Reassignable?NoYes
Block-scoped?YesYes
Use forValues that never changeValues that change (counters, state)
const PI = 3.14159;
// PI = 3;  // ✗ Error — cannot reassign a const

let count = 0;
count = count + 1;  // ✓ OK
count++;            // ✓ Same thing

// const with objects/arrays — the reference is const, not the content
const user = { name: "Alice" };
user.name = "Bob";  // ✓ Fine — mutating the object, not reassigning the variable
user = {};          // ✗ Error

Naming Rules

// ✓ Valid names
let firstName = "Alice";   // camelCase — standard for JS
let _private  = true;
let $element  = null;
let count2    = 0;

// ✗ Invalid
// let 2count = 0;    // cannot start with a digit
// let my-var = 0;   // hyphens not allowed
// let class  = 0;   // reserved word
Default to const. Only use let when you know the value will change. Never use var — it has confusing scoping rules that cause bugs.
🧩

Test Yourself

4 questions
Q1.Which keyword declares a block-scoped variable that CAN be reassigned?
Q2.What happens when you try to reassign a const variable?
Q3.Which of these is a valid JavaScript variable name?
Q4.Which keyword should you avoid in modern JavaScript?