Skip to main content

Command Palette

Search for a command to run...

Keywords - Let, Const, Var in Js

Published
β€’2 min read

πŸ”‘ 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

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
Redeclarationβœ… Allowed❌ Not allowed❌ Not allowed
Reassignmentβœ… Allowedβœ… Allowed❌ Not allowed
Hoisting (moved up)βœ… Yes🚫 Not fully🚫 Not fully

βœ… Rule of Thumb:

  • Use const by default.

  • Use let if the value needs to change.

  • Avoid var unless you’re working with old code.