JavaScript Variables: Var, Let, Const Explained

Variables in JavaScript In JavaScript, variables can be declared using var, let, or const. 1. var – Function Scoped The var keyword was the original way to declare variables in JavaScript. A variable declared with var is function-scoped, meaning it can be accessed anywhere inside the function where it is defined — even outside of a block like an if statement. Example: function testVar() { if (true) { var message = "Hello, world!"; // declared with var } console.log(message); // accessible here because var is function-scoped } testVar(); // Output: "Hello, world!" Here, the variable message is accessible outside the if block because var does not have block scope—it only respects function boundaries. 2. let and const – Block Scoped Introduced in ES6 (ECMAScript 2015), both let and const are block-scoped. That means variables declared with these keywords can only be accessed within the block { } where they are defined. let allows you to reassign the variable later. const creates a read-only (constant) variable that cannot be reassigned once set. Example: function testBlockScope() { if (true) { let name = "Adnan"; // block-scoped const age = 25; // block-scoped and read-only console.log(name, age); // Accessible here → Adnan 25 } // console.log(name); // Error! 'name' is not defined outside the block // console.log(age); // Error! 'age' is not defined outside the block } testBlockScope(); In this case, name and age are not accessible outside the if block because both let and const follow block scope rules.

var can lead to unexpected behavior due to its function scope, while let and const provide safer, predictable block scoping.

To view or add a comment, sign in

Explore content categories