Variables and constants

In JavaScript, variables are used to store data values, and constants hold values that do not change. There are three ways to declare variables: var, let, and const.

1. Declaring Variables

JavaScript provides two modern ways (let and var) and one older way (var) to declare variables.

1.1 Using var (Old Way, Avoid Using)

  • Can be redeclared within the same scope.
  • Function-scoped (not block-scoped).
  • May lead to unexpected behavior due to hoisting.
var name = "Alice"; 
console.log(name); // Output: Alice
var name = "Bob"; // Redeclaration is allowed
console.log(name); // Output: Bob

🔹 Why avoid var?

Since var does not respect block scope, it can cause unexpected issues in larger programs.

1.2 Using let (Modern & Recommended)

Block-scoped (only available inside {} where declared).

Can be updated but not redeclared in the same scope.

let age = 25;
console.log(age); // Output: 25
age = 30; // Allowed: Updating the variable
console.log(age); // Output: 30
// let age = 40; ❌ Error: Cannot redeclare the variable

🔹 Best practice: Use let for values that may change.

2. Declaring Constants (const)

  • Block-scoped like let.
  • Cannot be reassigned after initialization.
  • Must be initialized when declared.
const PI = 3.14;
console.log(PI); // Output: 3.14
// PI = 3.14159; ❌ Error: Cannot reassign a constant

🔹 Best practice: Use const for values that should not change (e.g., mathematical constants, API keys).

Scope of Variables

JavaScript variables have different scopes depending on how they are declared:

Variable TypeScopeCan be Updated?Can be Redeclared?Hoisted?
varFunction✅ Yes✅ Yes✅ Yes (with undefined)
letBlock✅ Yes❌ No❌ No
constBlock❌ No❌ No❌ No
Latest Current Affairs 2025 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2025 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz