JavaScript Variables Tutorial – var, let, const & Scope
Module 2 — Variables
Variables are one of the most fundamental concepts in JavaScript. Every application, from a simple calculator to a large web platform, relies on variables to store and manipulate data.
In this module, you will learn:
- What variables are
- How to declare variables
- The differences between
var,let, andconst - Variable scope
- Block scope
- Hoisting
- Temporal Dead Zone (TDZ)
- Variable naming rules
- Best practices
What is a Variable?
A variable is a named container used to store data in memory. You can later read, update, or manipulate the stored value.
Think of a variable like a labeled box:
1username ──► "Ankit" 2age ──► 23 3isAdmin ──► false
Why Do We Need Variables?
Variables allow us to:
- Store user input
- Save API responses
- Perform calculations
- Track application state
- Reuse values throughout a program
Example:
1let username = "Ankit"; 2let age = 23; 3 4console.log(username); 5console.log(age);
Output
1Ankit 223
Declaring Variables
JavaScript provides three ways to declare variables:
varletconst
The var Keyword
Before ES6, var was the only way to declare variables.
Syntax
1var message = "Hello JavaScript"; 2console.log(message);
Output
1Hello JavaScript
Updating a var
1var city = "Delhi"; 2 3city = "Noida"; 4 5console.log(city);
Output
1Noida
Redeclaring a var
1var score = 80; 2var score = 95; 3 4console.log(score);
Output
195
var allows both reassignment and redeclaration, which can lead to bugs in larger applications.
The let Keyword
let was introduced in ECMAScript 2015 (ES6). It is now the preferred way to declare variables whose values may change.
Syntax
1let language = "JavaScript"; 2 3console.log(language);
Reassigning
1let age = 22; 2 3age = 23; 4 5console.log(age);
Output
123
Redeclaration Error
1let age = 22; 2let age = 25;
Output
1SyntaxError: Identifier 'age' has already been declared
let allows reassignment but does not allow redeclaration within the same scope.
The const Keyword
Use const when the variable should not be reassigned.
Syntax
1const PI = 3.14159; 2 3console.log(PI);
Reassignment Error
1const PI = 3.14; 2 3PI = 3.14159;
Output
1TypeError: Assignment to constant variable.
const with Objects
Although the variable cannot point to a different object, the object's contents can still change.
1const user = { 2 name: "Ankit", 3 age: 23 4}; 5 6user.age = 24; 7 8console.log(user);
Output
1{ 2 name: "Ankit", 3 age: 24 4}
const with Arrays
1const colors = ["Red", "Blue"]; 2 3colors.push("Green"); 4 5console.log(colors);
Output
1["Red", "Blue", "Green"]
The array contents changed, but the variable still references the same array.
Variable Scope
Scope determines where a variable is accessible.
JavaScript has three main scopes:
- Global Scope
- Function Scope
- Block Scope
Global Scope
Variables declared outside any function or block are globally accessible.
1let appName = "Tech3Space"; 2 3function showApp() { 4 console.log(appName); 5} 6 7showApp(); 8console.log(appName);
Output
1Tech3Space 2Tech3Space
Function Scope
Variables declared inside a function are available only within that function.
1function greet() { 2 let message = "Hello"; 3 console.log(message); 4} 5 6greet(); 7 8// console.log(message);
Trying to access message outside the function results in a ReferenceError.
Block Scope
A block is any code enclosed in {}.
Variables declared with let and const are block-scoped.
1if (true) { 2 let score = 100; 3 console.log(score); 4} 5 6// console.log(score);
Output
1100 2ReferenceError
var is Not Block Scoped
1if (true) { 2 var city = "Delhi"; 3} 4 5console.log(city);
Output
1Delhi
This is one reason why var is discouraged in modern JavaScript.
Hoisting
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase.
Hoisting with var
1console.log(name); 2 3var name = "Ankit";
Internally, JavaScript interprets it like this:
1var name; 2 3console.log(name); 4 5name = "Ankit";
Output
1undefined
Hoisting with let
1console.log(age); 2 3let age = 23;
Output
1ReferenceError
Hoisting with const
1console.log(PI); 2 3const PI = 3.14;
Output
1ReferenceError
Temporal Dead Zone (TDZ)
The Temporal Dead Zone (TDZ) is the period between entering a scope and initializing a let or const variable.
During this period, the variable exists but cannot be accessed.
1{ 2 console.log(username); 3 4 let username = "Ankit"; 5}
Output
1ReferenceError
Once initialized, the variable can be used normally.
1{ 2 let username = "Ankit"; 3 4 console.log(username); 5}
Output
1Ankit
Variable Naming Rules
Valid examples:
1let username; 2let userName; 3let user_name; 4let user1; 5let $price; 6let _count;
Invalid examples:
1let 123name; 2let user-name; 3let let;
Naming Best Practices
Use descriptive names:
1let totalPrice; 2let userEmail; 3let productCount; 4let currentBalance;
Avoid unclear names:
1let x; 2let a; 3let temp1;
Use constants in uppercase:
1const MAX_USERS = 100; 2const API_URL = "https://api.example.com";
Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Redeclare | ✅ Yes | ❌ No | ❌ No |
| Reassign | ✅ Yes | ✅ Yes | ❌ No |
| Block Scope | ❌ No | ✅ Yes | ✅ Yes |
| Hoisted | ✅ Yes | ✅ Yes (TDZ) | ✅ Yes (TDZ) |
| Default Choice | ❌ No | ✅ Often | ✅ Preferred when value doesn't change |
Best Practices
- Prefer
constby default. - Use
letwhen reassignment is required. - Avoid using
varin modern JavaScript. - Use meaningful variable names.
- Keep variable scope as small as possible.
- Declare variables close to where they are used.
- Follow consistent naming conventions throughout your project.
Mini Project: User Profile
HTML
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Variables Demo</title> 7</head> 8<body> 9 10<h2>User Information</h2> 11 12<p id="output"></p> 13 14<script src="script.js"></script> 15 16</body> 17</html>
JavaScript (script.js)
1"use strict"; 2 3const username = "Ankit"; 4let age = 23; 5const country = "India"; 6 7age = 24; 8 9const output = document.getElementById("output"); 10 11output.innerHTML = ` 12 <strong>Name:</strong> ${username}<br> 13 <strong>Age:</strong> ${age}<br> 14 <strong>Country:</strong> ${country} 15`;
Common Mistakes
1// ❌ Using var unnecessarily 2var count = 10; 3 4// ✅ Use let 5let count = 10;
1// ❌ Reassigning a constant 2const PI = 3.14; 3PI = 3.14159;
1// ❌ Accessing a variable before initialization 2console.log(name); 3let name = "Ankit";
Summary
In this module, you learned:
- What variables are and why they are essential.
- How to declare variables using
var,let, andconst. - The key differences between these three declaration keywords.
- Global, function, and block scope.
- How hoisting works in JavaScript.
- What the Temporal Dead Zone (TDZ) is and why it matters.
- Variable naming rules and recommended conventions.
- Modern best practices for writing clean, maintainable JavaScript code.
With a solid understanding of variables, you are ready to move on to Module 3, where you'll explore JavaScript Data Types, including primitive types, reference types, type checking, and type conversion.