JavaScript Tutorial

Variables in JavaScript: Complete Guide for Beginners

Learn everything about JavaScript variables, naming rules, and the differences between var, let, and const. Master variable declaration, initialization, and best practices.

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 age stores someone's age
  • A variable named userName stores a user's name
  • A variable named price stores 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:

  1. var (old way, avoid in modern code)
  2. let (modern, for values that change)
  3. const (modern, for values that don't change)

Basic Syntax

let variableName = value;

Components:

  • let - The declaration keyword
  • variableName - The name you choose for your variable
  • = - Assignment operator
  • value - 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.50

Declaration vs Initialization

Declaration: Creating a variable (reserving memory)

let name; // Declared but not initialized
console.log(name); // Output: undefined

Initialization: Assigning a value to the variable

let name;
name = "Mihir"; // Now initialized
console.log(name); // Output: Mihir

Declaration + Initialization (in one line):

let name = "Mihir"; // Declared and initialized together

Multiple 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 spaces

2. 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 allowed

3. 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 separation

What 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 style

5. 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 plural

7. 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 calculated

Naming 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

Featurevarletconst
ScopeFunction scopeBlock scopeBlock scope
Reassignmentāœ… Yesāœ… YesāŒ No
Redeclarationāœ… YesāŒ NoāŒ No
HoistingYes (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);     // 5

Global 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); // 15

Temporal 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 defined

2. Values that change:

let score = 0;
score = score + 10;  // Update score
score += 5;          // Update again

3. 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 declaration

Cannot Be Reassigned

const PI = 3.14159;
PI = 3.14; // āŒ TypeError: Assignment to constant variable

const userName = "John";
userName = "Jane"; // āŒ TypeError: Assignment to constant variable

Block Scoped (Like let)

if (true) {
  const x = 10;
  console.log(x); // 10
}
console.log(x); // āŒ ReferenceError: x is not defined

Important: 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 variable

Why? 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 variable

When 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, temporaryValue

Practical 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 reassigned

Example 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" }; // Error

Variable 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); // āœ… Accessible

Function Scope

function test() {
  const localVar = "I'm local";
  console.log(localVar); // āœ… Accessible
}

test();
console.log(localVar); // āŒ ReferenceError

Block 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); // āŒ ReferenceError

Block Scope Does NOT Apply to var

if (true) {
  var notBlockScoped = "I escape!";
}

console.log(notBlockScoped); // āœ… "I escape!" - var ignores block scope

Common 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.js

Key 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:

  1. āœ… Use const by default
  2. āœ… Use let only when reassignment is needed
  3. āŒ Avoid var completely in new code
  4. āœ… Use meaningful, descriptive names
  5. āœ… Follow camelCase convention
  6. āœ… Declare variables before using them
  7. āœ… Keep variables in the smallest scope possible
  8. āœ… Use UPPERCASE for true constants
  9. āœ… Boolean variables should sound like yes/no questions
  10. āœ… Be consistent with your naming patterns

Practice Exercise

Challenge: Create a Student Information System

Create a file called student-info.js with:

  1. Declare constants for:

    • School name
    • Current year
    • Maximum students allowed
  2. 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)
  3. Print all information

  4. Update grade, GPA, and add a course

  5. 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 statements

Try 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!