Js Variables in JavaScript
JavaScript Variables
Variables are containers used to store data values. In JavaScript, you declare variables using let, const, or var.
1. Declaring Variables
a) let (Block-scoped, mutable)
let name = "Alice";name = "Bob"; // You can change the valueScope: limited to the block (
{ }) it is defined in.Use for variables whose values may change.
b) const (Block-scoped, immutable)
const PI = 3.14;Value cannot be reassigned after initialization.
Use for constants or variables that shouldn't change.
Note: For objects and arrays declared with
const, the reference is constant, but object properties or array elements can still be modified.
const arr = [1, 2, 3];arr.push(4); // Allowedarr = [5]; // Errorc) var (Function-scoped, mutable) — Avoid using in modern JS
var age = 25;age = 26;Has function scope, not block scope.
Hoisted differently compared to
letandconst.Generally avoided now due to confusing scoping behavior.
2. Variable Naming Rules
Must start with a letter,
$, or_.Subsequent characters can be letters, digits,
$, or_.Case-sensitive (
myVarandmyvarare different).Cannot be a reserved keyword (e.g.,
for,if,class).
3. Example
let message = "Hello";const year = 2025;message = "Hi"; // OK// year = 2026; // Error: assignment to constant variableconsole.log(message); // Hiconsole.log(year); // 20254. Hoisting (Brief)
vardeclarations are hoisted (moved to the top of scope), initialized asundefined.letandconstare hoisted but not initialized — accessing them before declaration causes an error.
If you want, I can explain hoisting in detail or show examples of scoping with var, let, and const!