Hey everyone! š Welcome to the JavaScript Fundamentals section. Now that you have Node.js installed and understand how JavaScript executes, it's time to learn one of the most fundamental concepts in programming: Variables.
Variables are containers that store data values. Think of them as labeled boxes where you can put information and retrieve it later. In this lesson, you'll learn everything about variables, how to name them properly, and the differences between var, let, and const.
Let's dive in!
What are Variables?
A variable is a named storage location in your computer's memory where you can store data that can be used and manipulated throughout your program.
Real-World Analogy
Think of variables like labeled containers in your kitchen:
- A jar labeled "Sugar" contains sugar
- A jar labeled "Coffee" contains coffee
- A jar labeled "Rice" contains rice
Similarly, in programming:
- A variable named
agestores someone's age - A variable named
userNamestores a user's name - A variable named
pricestores a product price
Why Do We Need Variables?
Without variables, you'd have to hardcode every value, making your code inflexible and difficult to maintain.
Without variables (bad):
console.log("Hello, John!");
console.log("John is 25 years old");
console.log("John's email is john@example.com");
// If John's name changes, you need to update 3 places!With variables (good):
let name = "John";
let age = 25;
let email = "john@example.com";
console.log("Hello, " + name + "!");
console.log(name + " is " + age + " years old");
console.log(name + "'s email is " + email);
// Change just one place, and it updates everywhere!Declaring Variables in JavaScript
JavaScript provides three keywords to declare variables:
var(old way, avoid in modern code)let(modern, for values that change)const(modern, for values that don't change)
Basic Syntax
let variableName = value;Components:
let- The declaration keywordvariableName- The name you choose for your variable=- Assignment operatorvalue- The data you want to store
Example: Your First Variables
// Declaring and initializing variables
let firstName = "Mihir";
let age = 30;
let isStudent = false;
let salary = 75000.50;
// Using the variables
console.log(firstName); // Output: Mihir
console.log(age); // Output: 30
console.log(isStudent); // Output: false
console.log(salary); // Output: 75000.50Declaration vs Initialization
Declaration: Creating a variable (reserving memory)
let name; // Declared but not initialized
console.log(name); // Output: undefinedInitialization: Assigning a value to the variable
let name;
name = "Mihir"; // Now initialized
console.log(name); // Output: MihirDeclaration + Initialization (in one line):
let name = "Mihir"; // Declared and initialized togetherMultiple Variable Declaration
Method 1: Separate lines (recommended for readability)
let firstName = "Mihir";
let lastName = "Patel";
let age = 30;Method 2: Single line with commas
let firstName = "Mihir", lastName = "Patel", age = 30;Method 3: Multiple declarations without initialization
let x, y, z;
x = 10;
y = 20;
z = 30;Variable Naming Rules
Choosing good variable names is crucial for writing clean, readable code. JavaScript has strict rules about what's allowed and best practices for what's recommended.
Rules You Must Follow (Syntax Rules)
These are mandatory - breaking them will cause errors.
1. Variables must start with:
- A letter (a-z, A-Z)
- An underscore (_)
- A dollar sign ($)
// Valid
let name = "Mihir";
let _private = "secret";
let $price = 100;
// Invalid - will cause errors
let 1name = "Mihir"; // ā Cannot start with number
let my-name = "Mihir"; // ā Cannot contain hyphen
let my name = "Mihir"; // ā Cannot contain spaces2. After the first character, you can use:
- Letters (a-z, A-Z)
- Numbers (0-9)
- Underscores (_)
- Dollar signs ($)
// Valid
let user1 = "John";
let user_name = "Jane";
let $amount = 500;
let firstName2 = "Bob";
// Invalid
let user-name = "John"; // ā Hyphen not allowed
let user name = "John"; // ā Space not allowed
let user@name = "John"; // ā Special characters not allowed3. Variable names are case-sensitive
let name = "Mihir";
let Name = "John";
let NAME = "Jane";
console.log(name); // "Mihir"
console.log(Name); // "John"
console.log(NAME); // "Jane"
// These are three different variables!4. Cannot use reserved keywords
JavaScript has reserved words that you cannot use as variable names:
// Invalid - reserved keywords
let let = 5; // ā
let const = 10; // ā
let function = 20; // ā
let return = 30; // ā
let if = 40; // ā
let for = 50; // āCommon reserved keywords to avoid:
break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, finally, for, function, if, import, in, instanceof, let, new, return, super, switch, this, throw, try, typeof, var, void, while, with, yield
Best Practices for Naming Variables
These are recommendations - following them makes your code more professional and maintainable.
1. Use camelCase for variable names
// Good - camelCase
let firstName = "Mihir";
let lastName = "Patel";
let userAge = 30;
let totalPrice = 1500;
let isLoggedIn = true;
// Avoid - other styles
let first_name = "Mihir"; // snake_case (used in Python)
let FirstName = "Mihir"; // PascalCase (used for classes)
let firstname = "Mihir"; // no separationWhat is camelCase?
- First word lowercase
- Each subsequent word starts with uppercase
- No spaces or special characters
- Example:
myVariableName,totalAmountDue,userAccountNumber
2. Use descriptive names
// Good - descriptive
let studentName = "John";
let productPrice = 499.99;
let isEmailVerified = true;
let userAge = 25;
// Bad - unclear
let n = "John"; // What is 'n'?
let p = 499.99; // What is 'p'?
let flag = true; // What flag?
let x = 25; // What does 'x' represent?3. Be specific and meaningful
// Good
let monthlyIncome = 5000;
let dailyTaskCount = 10;
let customerEmailAddress = "customer@example.com";
// Bad - too vague
let income = 5000; // Monthly? Yearly? Weekly?
let count = 10; // Count of what?
let email = "customer@example.com"; // Whose email?4. Use consistent naming patterns
// Good - consistent pattern
let firstName = "John";
let lastName = "Doe";
let middleName = "Smith";
// Bad - inconsistent
let firstName = "John";
let last_name = "Doe"; // Different style
let MIDDLENAME = "Smith"; // Different style5. Boolean variables should sound like questions
// Good - clear true/false meaning
let isActive = true;
let hasPermission = false;
let canEdit = true;
let shouldUpdate = false;
let hasError = true;
// Bad - unclear
let active = true; // Not as clear
let permission = false; // Confusing
let edit = true; // What about edit?6. Use plural names for arrays/collections
// Good
let students = ["John", "Jane", "Bob"];
let prices = [10, 20, 30];
let users = [];
// Bad
let student = ["John", "Jane", "Bob"]; // Confusing - sounds like one
let price = [10, 20, 30]; // Should be plural7. Avoid single-letter names (except in loops)
// Good - meaningful names
let count = 0;
let total = 100;
let index = 5;
// Acceptable - loop counters
for (let i = 0; i < 10; i++) {
console.log(i);
}
// Bad - unclear single letters
let a = 0; // What is 'a'?
let x = 100; // What is 'x'?
let z = 5; // What is 'z'?8. Constants should be in UPPERCASE
For truly constant values that never change:
// Good - SCREAMING_SNAKE_CASE for constants
const MAX_USERS = 100;
const API_KEY = "abc123xyz";
const DATABASE_URL = "https://db.example.com";
const PI = 3.14159;
// Regular const variables can use camelCase
const userName = "Mihir"; // This might come from user input
const totalPrice = 150; // This might be calculatedNaming Examples: Good vs Bad
// ā BAD Examples
let x = "John Doe"; // Unclear
let temp = 25000; // Temporary what?
let data = []; // Too generic
let flag = true; // What flag?
let a1 = "test@example.com"; // Meaningless
let mgr = "Sarah"; // Abbreviation unclear
// ā
GOOD Examples
let customerFullName = "John Doe";
let annualSalary = 25000;
let productList = [];
let isFormValid = true;
let userEmailAddress = "test@example.com";
let departmentManager = "Sarah";var vs let vs const: Understanding the Differences
JavaScript has three ways to declare variables. Understanding when to use each is crucial for writing modern, bug-free code.
Quick Summary Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function scope | Block scope | Block scope |
| Reassignment | ā Yes | ā Yes | ā No |
| Redeclaration | ā Yes | ā No | ā No |
| Hoisting | Yes (initialized as undefined) | Yes (not initialized - TDZ) | Yes (not initialized - TDZ) |
| Usage | ā ļø Avoid (legacy) | ā Use for changing values | ā Use for constant values |
1. var (The Old Way - Avoid in Modern Code)
var was the only way to declare variables before ES6 (2015). It has confusing behavior and should be avoided in modern JavaScript.
Function Scope (Not Block Scope)
function testVar() {
var x = 10;
if (true) {
var x = 20; // Same variable! Not a new one
console.log(x); // 20
}
console.log(x); // 20 (changed!)
}
testVar();Problem: var ignores block scope (if, for, while), leading to unexpected behavior.
Redeclaration Allowed (Dangerous)
var name = "John";
var name = "Jane"; // No error! Overwrites silently
console.log(name); // "Jane"
// This can lead to bugs:
var userCount = 10;
// ... 100 lines of code later ...
var userCount = 5; // Accidentally overwrote!Hoisting with Initialization
console.log(x); // undefined (not an error)
var x = 5;
console.log(x); // 5
// JavaScript interprets it as:
// var x; // Hoisted and initialized to undefined
// console.log(x); // undefined
// x = 5;
// console.log(x); // 5Global Object Pollution
var globalVar = "I'm global";
console.log(window.globalVar); // "I'm global" (in browsers)
// var creates properties on global object - can cause conflicts!Why avoid var?
- Function-scoped (not block-scoped) - confusing
- Allows redeclaration - error-prone
- Pollutes global object
- Harder to debug
- No advantage over let/const
2. let (Modern Way for Changing Values)
let was introduced in ES6 (2015) and fixes all the problems with var.
Block Scope
function testLet() {
let x = 10;
if (true) {
let x = 20; // Different variable (new scope)
console.log(x); // 20
}
console.log(x); // 10 (original unchanged)
}
testLet();Benefit: Each block ({}) creates a new scope, preventing accidental overwrites.
No Redeclaration
let name = "John";
let name = "Jane"; // ā SyntaxError: Identifier 'name' has already been declared
// This catches bugs early!Reassignment Allowed
let count = 0;
console.log(count); // 0
count = 10;
console.log(count); // 10
count = count + 5;
console.log(count); // 15Temporal Dead Zone (TDZ)
console.log(x); // ā ReferenceError: Cannot access 'x' before initialization
let x = 5;
// let is hoisted but NOT initialized (unlike var)Benefit: Forces you to declare variables before using them, catching errors early.
Common Use Cases for let
1. Loop counters:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
console.log(i); // ā ReferenceError: i is not defined2. Values that change:
let score = 0;
score = score + 10; // Update score
score += 5; // Update again3. Conditional assignments:
let message;
if (isLoggedIn) {
message = "Welcome back!";
} else {
message = "Please log in";
}3. const (Modern Way for Constant Values)
const is like let but for values that shouldn't be reassigned.
Must Be Initialized
const name = "Mihir"; // ā
Good
const age; // ā SyntaxError: Missing initializer in const declarationCannot Be Reassigned
const PI = 3.14159;
PI = 3.14; // ā TypeError: Assignment to constant variable
const userName = "John";
userName = "Jane"; // ā TypeError: Assignment to constant variableBlock Scoped (Like let)
if (true) {
const x = 10;
console.log(x); // 10
}
console.log(x); // ā ReferenceError: x is not definedImportant: const Does NOT Make Objects Immutable
This is a common misconception:
const person = {
name: "John",
age: 30
};
// ā
You CAN modify object properties
person.name = "Jane";
person.age = 31;
console.log(person); // { name: "Jane", age: 31 }
// ā You CANNOT reassign the entire object
person = { name: "Bob" }; // TypeError: Assignment to constant variableWhy? const prevents reassignment of the variable itself, not mutation of the value it holds.
Same with arrays:
const colors = ["red", "blue"];
// ā
Can modify array contents
colors.push("green");
colors[0] = "yellow";
console.log(colors); // ["yellow", "blue", "green"]
// ā Cannot reassign array
colors = ["purple"]; // TypeError: Assignment to constant variableWhen to Use const
1. Values that never change:
const MAX_LOGIN_ATTEMPTS = 3;
const API_URL = "https://api.example.com";
const TAX_RATE = 0.08;2. Objects and arrays (even if contents change):
const user = { name: "John", age: 30 };
const items = [1, 2, 3];
// Contents can change, reference stays the same
user.age = 31;
items.push(4);3. Function declarations:
const calculateTotal = (price, quantity) => {
return price * quantity;
};4. Imported modules:
const fs = require('fs');
const express = require('express');When to Use var, let, or const?
Modern JavaScript Best Practice:
// ā
Default to const (95% of the time)
const userName = "Mihir";
const users = [];
const config = { debug: true };
// ā
Use let when value needs to change
let counter = 0;
let isLoggedIn = false;
let currentPage = 1;
// ā Never use var (unless maintaining legacy code)
var oldWay = "avoid this";Decision Tree:
Will this variable's value be reassigned?
ā
āā NO ā Use const
ā Examples: userName, PI, MAX_SIZE, users (array)
ā
āā YES ā Use let
Examples: counter, index, temporaryValuePractical Examples: Choosing the Right Keyword
Example 1: User Information
// ā
Good practice
const firstName = "Mihir"; // Won't change
const lastName = "Patel"; // Won't change
let age = 30; // Might change (birthdays!)
let isActive = true; // Status might change
// Later in code:
age = 31; // ā
Allowed (let)
// firstName = "John"; // ā Error (const)Example 2: Shopping Cart
// ā
Good practice
const cart = []; // Array reference won't change
let totalPrice = 0; // Total will change as items added
// Adding items
cart.push({ name: "Book", price: 20 });
cart.push({ name: "Pen", price: 5 });
totalPrice = 25;
// ā
cart contents changed, but reference didn't
// ā
totalPrice was reassignedExample 3: Loop Counter
// ā
Good - let for loop variable
for (let i = 0; i < 5; i++) {
console.log(i);
}
// ā Bad - const won't work here
for (const i = 0; i < 5; i++) { // ā Error: Assignment to constant
console.log(i);
}Example 4: Configuration
// ā
Good practice
const CONFIG = {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3
};
// ā
Can modify properties
CONFIG.timeout = 10000;
// ā Cannot reassign
// CONFIG = { apiUrl: "new-url" }; // ErrorVariable Scope Quick Review
Understanding scope is crucial (we covered this in the Execution Model lesson). Here's a quick refresher:
Global Scope
const globalVar = "I'm global";
function test() {
console.log(globalVar); // ā
Accessible
}
test();
console.log(globalVar); // ā
AccessibleFunction Scope
function test() {
const localVar = "I'm local";
console.log(localVar); // ā
Accessible
}
test();
console.log(localVar); // ā ReferenceErrorBlock Scope (let and const)
if (true) {
let blockVar = "I'm in a block";
const anotherBlockVar = "Me too";
console.log(blockVar); // ā
Accessible
}
console.log(blockVar); // ā ReferenceError
console.log(anotherBlockVar); // ā ReferenceErrorBlock Scope Does NOT Apply to var
if (true) {
var notBlockScoped = "I escape!";
}
console.log(notBlockScoped); // ā
"I escape!" - var ignores block scopeCommon Variable Mistakes and How to Avoid Them
Mistake 1: Using a Variable Before Declaration
// ā Bad
console.log(name);
let name = "Mihir";
// ReferenceError: Cannot access 'name' before initialization
// ā
Good
let name = "Mihir";
console.log(name);Mistake 2: Trying to Reassign const
// ā Bad
const age = 30;
age = 31;
// TypeError: Assignment to constant variable
// ā
Good - use let if value changes
let age = 30;
age = 31;Mistake 3: Forgetting to Declare
// ā Bad (creates accidental global)
function test() {
age = 30; // No var/let/const!
}
test();
console.log(age); // 30 (accidentally global!)
// ā
Good
function test() {
let age = 30;
}
test();
console.log(age); // ReferenceError (as expected)Mistake 4: Confusing Variable Names
// ā Bad
let user = "John";
let User = "Jane";
let USER = "Bob";
// All different variables - confusing!
// ā
Good
let firstName = "John";
let lastName = "Doe";
let userName = "johndoe";Mistake 5: Using var in Modern Code
// ā Bad - avoid var
var counter = 0;
for (var i = 0; i < 10; i++) {
// ...
}
// ā
Good - use let/const
let counter = 0;
for (let i = 0; i < 10; i++) {
// ...
}Practical Exercise: Variables in Action
Let's create a complete example using everything we've learned:
// Personal Information System
// Constants - values that don't change
const SYSTEM_NAME = "User Management System";
const VERSION = "1.0.0";
const MAX_NAME_LENGTH = 50;
// User information - some change, some don't
const userId = "USER_001"; // Unique ID - never changes
let userName = "Mihir Patel"; // Name might change
let userAge = 30; // Age changes yearly
let isActive = true; // Status might change
const dateCreated = "2024-02-13"; // Created date - never changes
// User preferences - object can be modified
const preferences = {
theme: "dark",
language: "en",
notifications: true
};
// Display information
console.log("=== " + SYSTEM_NAME + " v" + VERSION + " ===");
console.log("User ID:", userId);
console.log("Name:", userName);
console.log("Age:", userAge);
console.log("Active:", isActive);
console.log("Member Since:", dateCreated);
// Modify changeable values
userAge = 31; // Birthday!
preferences.theme = "light"; // Changed preference
isActive = false; // Account deactivated
// Display updated information
console.log("\n=== Updated Information ===");
console.log("Age:", userAge);
console.log("Theme:", preferences.theme);
console.log("Active:", isActive);
// Calculate something
let yearsAsMember = 2024 - 2023;
console.log("Years as member:", yearsAsMember);Try running this code! Save it as variables-demo.js and run:
node variables-demo.jsKey Takeaways
Congratulations! You now understand JavaScript variables. Here's what you learned:
ā What variables are - containers for storing data values
ā How to declare variables - using let, const, and (avoid) var
ā Variable naming rules - must follow syntax rules and best practices
ā Naming conventions - camelCase, descriptive names, meaningful identifiers
ā var vs let vs const - differences in scope, reassignment, and modern usage
ā When to use each:
- const - Default choice (95% of the time)
- let - When value needs to change
- var - Never (legacy code only)
ā Common mistakes - and how to avoid them
Best Practices Summary
Always Remember:
- ā
Use
constby default - ā
Use
letonly when reassignment is needed - ā Avoid
varcompletely in new code - ā Use meaningful, descriptive names
- ā Follow camelCase convention
- ā Declare variables before using them
- ā Keep variables in the smallest scope possible
- ā Use UPPERCASE for true constants
- ā Boolean variables should sound like yes/no questions
- ā Be consistent with your naming patterns
Practice Exercise
Challenge: Create a Student Information System
Create a file called student-info.js with:
-
Declare constants for:
- School name
- Current year
- Maximum students allowed
-
Declare variables for a student:
- Student ID (doesn't change)
- First name (doesn't change)
- Last name (doesn't change)
- Current grade (changes yearly)
- GPA (changes each semester)
- Is enrolled (status might change)
- Courses (array - can add/remove courses)
-
Print all information
-
Update grade, GPA, and add a course
-
Print updated information
Solution structure:
// Constants
const SCHOOL_NAME = "JavaScript Academy";
const CURRENT_YEAR = 2024;
const MAX_STUDENTS = 500;
// Student info
const studentId = "STU_001";
// ... add more variables
// Display initial info
console.log("=== Student Information ===");
// ... add console.log statements
// Update some values
// ... modify changeable values
// Display updated info
console.log("\n=== Updated Information ===");
// ... add console.log statementsTry to complete this exercise before moving to the next lesson!
What's Next?
Great job! š You now have a solid understanding of variables in JavaScript.
In the next lesson, we'll dive deeper into Data Types where you'll learn:
- Primitive data types (String, Number, Boolean, etc.)
- Reference types (Objects, Arrays)
- Type checking with
typeof - Type conversion and coercion
Variables store data, but what kind of data can they store? That's what we'll explore next!