Keywords - Let, Const, Var in Js
π Keywords in JavaScript (var, let, const)
keywords are reserved words that have a special meaning in the language.
π You cannot use them as variable names, function names, or identifiers because JavaScript uses them for its own purposes.
In JavaScript, variables are used to store data values (like numbers, strings, or objects).
To declare a variable, we use special keywords:
1. var (Old Way)
Introduced in the early versions of JavaScript.
Function-scoped (visible inside the function where itβs declared).
Can be redeclared and updated.
Not commonly used today because it can cause unexpected behavior.
var name = "Priyanshu";
console.log(name); // Priyanshu
var name = "Coder"; // Redeclaration allowed
console.log(name); // Coder
Problem: var ignores block scope (like inside {}), which can be confusing.
2. let (Modern Way)
Introduced in ES6 (2015).
Block-scoped (only works inside the
{}where itβs defined).Can be updated but not redeclared in the same scope.
let age = 20;
console.log(age); // 20
age = 21; // β
allowed (update)
console.log(age); // 21
// let age = 30; β Error (redeclare not allowed in the same scope)
π Best for values that need to change.
3. const (Constant)
Also introduced in ES6 (2015).
Block-scoped (like
let).Cannot be redeclared or updated.
Must be initialized at the time of declaration.
const pi = 3.14;
console.log(pi); // 3.14
// pi = 3.1415; β Error (cannot update)
// const pi = 22/7; β Error (cannot redeclare)
π Best for values that should never change (like configurations, API keys, constants).
β‘ Quick Comparison
| Feature | var | let | const |
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Redeclaration | β Allowed | β Not allowed | β Not allowed |
| Reassignment | β Allowed | β Allowed | β Not allowed |
| Hoisting (moved up) | β Yes | π« Not fully | π« Not fully |
β Rule of Thumb:
Use
constby default.Use
letif the value needs to change.Avoid
varunless youβre working with old code.