🧮 JavaScript Variables & Data Types
Estimated reading: 3 minutes 10 views

🧠 JavaScript var Keyword – Complete Syntax & Scope Guide

The var keyword is one of the three ways to declare variables in JavaScript — the other two being let and const.

Although var is older and less preferred in modern JavaScript due to scoping issues, it’s important to understand for legacy codebases, interview prep, and debugging older scripts.


✅ Syntax of var

var variableName = value;

📌 Example:

var city = "New York";
console.log(city);

🔍 Code Explanation:

CodeExplanation
varDeclares a variable using the traditional keyword
cityName of the variable (identifier)
=Assignment operator
"New York"Value assigned to the variable
console.log(...)Outputs the variable’s value to the console

🧩 Features of var

🔹 1. Function Scope (NOT Block Scoped)

Variables declared with var are scoped to the function, not the block ({}).

function greet() {
if (true) {
var message = "Hello!";
}
console.log(message); // ✅ Outputs: Hello!
}
greet();

✔️ message is accessible outside the if block because var does not honor block scoping.


🔹 2. Variable Hoisting

Variables declared with var are hoisted to the top of their scope, but not their values.

console.log(age); // ✅ Outputs: undefined
var age = 30;

🔍 Internally, JavaScript interprets this as:

var age;
console.log(age); // undefined
age = 30;

⚠️ Note: Only the declaration is hoisted, not the initialization.


🔹 3. Redeclaration is Allowed

You can redeclare a variable in the same scope with var.

var name = "Alice";
var name = "Bob";
console.log(name); // ✅ Outputs: Bob

⚠️ This can lead to accidental overwriting of variables — a key reason let and const were introduced.


🔹 4. Can Be Reassigned

Just like let, variables declared with var can be reassigned.

var score = 100;
score = 200;
console.log(score); // ✅ Outputs: 200

📊 Comparison Table: var vs let vs const

Featurevarletconst
ScopeFunctionBlockBlock
HoistingYes (as undefined)Yes (but no use before declaration)Yes (but no use before declaration)
Redeclaration✅ Allowed❌ Error❌ Error
Reassignment✅ Allowed✅ Allowed❌ Not Allowed
Use CaseLegacy codeGeneral useImmutable values

🧪 Practical Example: Why var Can Be Problematic

for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i); // Outputs 3, 3, 3
}, 1000);
}

🔍 Why?

  • var is function-scoped, so all callbacks share the same i.
  • The loop finishes, i becomes 3, and then all setTimeouts run with i = 3.

Fix with let:

for (let i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i); // Outputs 0, 1, 2
}, 1000);
}

💬 Best Practices with var

🔸 Avoid using var in modern code unless:

  • You’re maintaining legacy applications
  • You explicitly need function-scoped behavior

🔸 Prefer let or const:

  • const for values that never change
  • let for values that might change

🧠 Summary

The var keyword was the only way to declare variables in JavaScript until ES6 introduced let and const. While it’s still valid, var comes with caveats like hoisting, redeclaration, and lack of block scope that can cause bugs in large applications.

📌 What You Learned:

  • Syntax and features of var
  • How hoisting and scoping work
  • Why modern JavaScript prefers let and const
  • Real-world pitfalls with var

❓FAQ: JavaScript var

❓ What is the scope of var in JavaScript?

➡️ var is function-scoped, meaning it is accessible throughout the function where it is declared.

❓ Can you redeclare a variable with var?

➡️ Yes, JavaScript allows redeclaration of the same variable within the same scope using var.

❓ Is var hoisted?

➡️ Yes, but only the declaration is hoisted, not the value.

❓ Should I use var or let/const in modern code?

➡️ Prefer let or const for safer, more predictable scoping behavior.

❓ Can I use var inside if or for blocks?

➡️ Yes, but remember: the variable will not be block-scoped — it will belong to the entire function.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — var Keyword

Or Copy Link

CONTENTS
Scroll to Top