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 JSconst vs let
| const | let | |
|---|---|---|
| Reassignable? | No | Yes |
| Block-scoped? | Yes | Yes |
| Use for | Values that never change | Values 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 = {}; // ✗ ErrorNaming 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 wordDefault to
const. Only use let when you know the value will change. Never use var — it has confusing scoping rules that cause bugs.