Skip to main content

Variables

What is a Variable?​

Imagine you have a box where you can store things. You label the box so you remember what's inside. In programming, a variable is exactly like that labeled boxβ€”it's a named container that stores information in your computer's memory.

Real-World Analogy πŸ“¦β€‹

Think of variables like labeled containers in your kitchen:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SUGAR β”‚ β”‚ FLOUR β”‚ β”‚ EGGS β”‚
β”‚ ------ β”‚ β”‚ ------ β”‚ β”‚ ------ β”‚
β”‚ 2 cups β”‚ β”‚ 5 cups β”‚ β”‚ 6 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
↑ Variable name ↑ Variable name ↑ Variable name
↓ Value ↓ Value ↓ Value

In JavaScript, this looks like:

let sugar = 2; // Container labeled "sugar" holds the value 2
let flour = 5; // Container labeled "flour" holds the value 5
let eggs = 6; // Container labeled "eggs" holds the value 6

Why Do We Need Variables?​

Computer programs are all about storing and manipulating data. Variables let you:

  • πŸ’Ύ Store information to use later
  • πŸ”„ Change values as your program runs
  • πŸ“ Give meaningful names to data (easier than remembering memory addresses!)
  • ♻️ Reuse values throughout your code

Example: Without Variables (Bad! 😡)

console.log(25 + 5); // Calculate age next year
console.log(25 - 5); // Calculate age 5 years ago
console.log(25 * 2); // Calculate double the age

What if the age changes? You'd have to update it in 3 places!

Example: With Variables (Good! βœ…)

let age = 25; // Store age once
console.log(age + 5); // Calculate age next year
console.log(age - 5); // Calculate age 5 years ago
console.log(age * 2); // Calculate double the age

// Need to change? Update in ONE place!
age = 30; // Now all calculations use 30

img_2.png

How to Declare a Variable​

To create a variable in JavaScript, you must declare it using a special keyword. Declaring a variable means:

  1. Giving it a name
  2. Reserving space in memory for its value

JavaScript gives you three ways to declare variables:

const ← Use this most of the time (values that won't change)
let ← Use when the value will change
var ← ❌ Avoid this (old and problematic)

Quick Decision Guide πŸŽ―β€‹

// Value won't change? Use const
const birthYear = 1995; // Birth year never changes
const PI = 3.14159; // Math constants never change
const companyName = "TechCorp"; // Company name won't change

// Value will change? Use let
let age = 25; // Age increases every year
let score = 0; // Score changes as game progresses
let currentPage = 1; // Page number changes when navigating

// Avoid var - it's old and confusing!
// We'll explain why later
JavaScript is Dynamically Typed

Unlike languages like C++, Java, or TypeScript, you don't need to specify the data type when declaring variables in JavaScript.

// In C++ or Java - you must specify the type
int age = 25; // Must say it's an integer
string name = "John"; // Must say it's a string
// In JavaScript - type is automatic!
let age = 25; // JavaScript knows it's a number
let name = "John"; // JavaScript knows it's a string

The keywords const, let, and var just declare the variable. JavaScript figures out the type from the value you assign.

Let's understand each keyword in detail:

const - For Values That Won't Change πŸ”’β€‹

The const keyword declares a variable that cannot be reassigned. Think of it as a locked containerβ€”once you put something in and lock it, you can't replace it with something else.

Key Rules:

  • βœ… Must assign a value immediately when declaring
  • ❌ Cannot reassign to a different value
  • βœ… Use for values that shouldn't change
  • πŸ“ Block-scoped (only accessible in the block where it's defined)
Basic const Example
const PI = 3.14159;
console.log(PI); // Output: 3.14159

PI = 3.14; // ❌ TypeError: Assignment to constant variable

Real-World Examples:

const daysInWeek = 7; // Never changes
const companyName = "TechCorp"; // Won't change in the app
const maxLoginAttempts = 3; // Fixed limit
const apiKey = "abc123xyz"; // Should remain constant
Important: const β‰  Immutable

const means the variable name can't point to a different value, but if the value is an object or array, you can still modify its contents!

const with Objects - You CAN Modify Properties
const person = {
name: "Alice",
age: 25
};

// βœ… This works! Changing properties inside the object
person.name = "Bob"; // Allowed!
person.age = 30; // Allowed!
console.log(person); // Output: { name: "Bob", age: 30 }

// ❌ This doesn't work! Replacing the entire object
person = { name: "Charlie", age: 35 }; // TypeError!

Think of it like this:

  • const person = A locked mailbox labeled "person"
  • You CAN change what's inside the mailbox
  • You CAN'T replace the mailbox itself
const with Arrays - You CAN Modify Elements
const colors = ["red", "blue", "green"];

// βœ… These work! Modifying the array contents
colors[0] = "yellow"; // Change first element
colors.push("purple"); // Add new element
console.log(colors); // Output: ["yellow", "blue", "green", "purple"]

// ❌ This doesn't work! Replacing the entire array
colors = ["orange", "pink"]; // TypeError!
When to Use const

Use const by default for:

  • Fixed values (PI, max limits, configuration)
  • Objects and arrays (even if you'll modify their contents)
  • Function declarations
  • Any value that shouldn't be reassigned

This prevents accidental reassignment bugs!

let - For Values That Can Change πŸ”„β€‹

The let keyword declares a variable that can be reassigned. Think of it as an unlocked containerβ€”you can change what's inside whenever you want.

Key Rules:

  • βœ… Can reassign to different values
  • ❌ Cannot declare the same variable name twice in the same scope
  • βœ… Can declare without an initial value
  • πŸ“ Block-scoped (only accessible in the block where it's defined)
Basic let Example
let score = 0; // Start with 0
console.log(score); // Output: 0

score = 10; // βœ… Change to 10
console.log(score); // Output: 10

score = 25; // βœ… Change again to 25
console.log(score); // Output: 25

Real-World Examples:

let playerHealth = 100; // Health decreases during game
let currentPage = 1; // Page number changes
let userInput = ""; // User types different things
let isLoggedIn = false; // Login status toggles
let itemsInCart = 0; // Cart count changes
let Can Be Declared Without a Value
let userName; // Declared but no value yet (undefined)
console.log(userName); // Output: undefined

userName = "Alice"; // Assign value later
console.log(userName); // Output: "Alice"
Can't Redeclare with let

You cannot declare the same variable name twice in the same scope:

let age = 25;
let age = 30; // ❌ SyntaxError: Identifier 'age' has already been declared

But you CAN reassign (update) the value:

let age = 25; // βœ… Declare
age = 30; // βœ… Reassign (no 'let' keyword)
console.log(age); // Output: 30

Visual Comparison:

// ❌ Wrong Way - Redeclaring
let count = 5;
let count = 10; // Error! Already declared

// βœ… Right Way - Reassigning
let count = 5;
count = 10; // Correct! Just updating the value
When to Use let

Use let when the value will change:

  • Loop counters (let i = 0)
  • Values that get updated (let score = 0)
  • Variables that change based on conditions
  • Temporary values that get reassigned

var - The Old Way (Avoid!) βš οΈβ€‹

The var keyword is the oldest way to declare variables in JavaScript. It still works, but it has confusing behaviors that cause bugs.

Problems with var:

  • ❌ Function-scoped (not block-scoped) - causes unexpected behavior
  • ❌ Can be redeclared in the same scope - leads to bugs
  • ❌ "Hoisting" makes it accessible before declaration - confusing!
  • ❌ No error if you accidentally redeclare - hard to debug
Example of var (Don't use this!)
var x = 5;
x = 10; // This is allowed

var x = 15; // This is ALSO allowed (but confusing!)
Why var is Problematic

Problem 1: var ignores blocks

if (true) {
var x = 5; // Declared inside block
}
console.log(x); // Output: 5 (accessible outside! 😱)
if (true) {
let y = 5; // Declared inside block
}
console.log(y); // ❌ Error: y is not defined (correct behavior)

Problem 2: var allows redeclaration

var name = "Alice";
// ...100 lines of code...
var name = "Bob"; // Oops! Accidentally overwrote the first one! πŸ›

// With let, this would error immediately
let name = "Alice";
let name = "Bob"; // ❌ Error! Caught the bug!

Problem 3: var hoisting is confusing

console.log(x); // Output: undefined (no error! πŸ˜•)
var x = 5;

console.log(y); // ❌ Error! (expected behavior)
let y = 5;
Modern JavaScript Best Practice

Never use var in new code! Always use const or let.

// ❌ Old way (2015 and earlier)
var name = "Alice";
var age = 25;

// βœ… Modern way (2015+)
const name = "Alice"; // Won't change
let age = 25; // Will change

You'll still see var in:

  • Old codebases (before 2015)
  • Legacy tutorials
  • Code that needs to support ancient browsers

But for your own code, stick with const and let!

Quick Reference: const vs let vs var πŸ“Šβ€‹

Featureconstletvar
Can reassign?❌ Noβœ… Yesβœ… Yes
Can redeclare?❌ No❌ Noβœ… Yes (bad!)
ScopeBlockBlockFunction (confusing!)
Must initialize?βœ… Yes❌ No❌ No
When to use?Default choiceWhen value changes❌ Never!

When to Use What? πŸŽ―β€‹

Follow this simple rule:

// 1. Start with const (default choice)
const userName = "Alice";
const maxAttempts = 3;
const colors = ["red", "blue"];

// 2. Switch to let only if you need to reassign
let score = 0;
score = score + 10; // Need to update? Use let

// 3. Never use var in modern JavaScript!
// var x = 5; ❌ Don't do this

Rule of Thumb:

  1. πŸ₯‡ Use const by default - Prevents accidental reassignment
  2. πŸ₯ˆ Use let when needed - Only when value will change
  3. 🚫 Never use var - Use const or let instead

Naming variables​

In JavaScript, you can use letters, digits, underscores, and dollar signs to name variables. You can also use Unicode letters. However, a variable name must begin with a letter, underscore, or dollar sign. You can't use a number to begin a variable name.

Example of valid and invalid variable names
// Valid variable names
let myName = "John";
let $myName = "John";
let _myName = "John";
let myName1 = "John";
let myName$ = "John";

// Invalid variable names
let 1myName = "John"; // SyntaxError: Unexpected strict mode reserved word
let my-name = "John"; // SyntaxError: Unexpected token '-'
let my name = "John"; // SyntaxError: Unexpected identifier
JavaScript is case-sensitive

JavaScript is case-sensitive. This means that myName and myname are different variables. It is a good practice to use camelCase for variable names. This means that the first word is in lowercase, and the first letter of each subsequent word is capitalized. For example, myName, myFirstName, myFavoriteColor, etc. You can also use underscores to separate words, but this is not recommended. For example, my_name, my_first_name, my_favorite_color, etc.

Reserved keywords​

JavaScript has many reserved keywords that you can't use as variable names. The following keywords can't be used as variable names:

  • break
  • case
  • catch
  • class
  • const
  • continue
  • debugger
  • default
  • delete
  • do
  • else
  • enum
  • export
  • etc.

A complete list of JavaScript keywords can be found here. If you use a reserved keyword as a variable name, you will get an error.

Using a reserved keyword as a variable name
let break = 5; // SyntaxError: Unexpected strict mode reserved word

Variable scope​

Scope in JavaScript refers to the accessibility and visibility of variables, functions, and objects within different parts of a codebase.

There are two types of scope:

Global scope​

Global scope refers to variables, functions, and objects that are defined outside any function and are accessible from anywhere in the codebase. For example:

Example of global scope
let globalVariable = "This is a global variable";

function myFunction() {
console.log(globalVariable);
}

myFunction(); // Output: "This is a global variable"

In this example, the variable globalVariable is defined outside any function and can be accessed by any function in the codebase, including myFunction().

Local scope​

Local scope refers to variables, functions, and objects that are defined within a function and are only accessible within that function. For example:

Example of local scope
function myFunction() {
let localVariable = "This is a local variable";
console.log(localVariable);
}

myFunction(); // Output: "This is a local variable"
console.log(localVariable); // ReferenceError: localVariable is not defined

In this example, the variable localVariable is defined within the myFunction() function and can only be accessed within that function. If we try to access it outside the function, we get a ReferenceError.

Variable shadowing​

It's important to note that local scope variables can "shadow" global scope variables with the same name. For example:

Example of variable shadowing
let globalVariable = "This is a global variable";

function myFunction() {
let globalVariable = "This is a local variable";
console.log(globalVariable);
}

myFunction(); // Output: "This is a local variable"
console.log(globalVariable); // Output: "This is a global variable"

In this example, the local variable globalVariable within myFunction() takes precedence over the global variable with the same name. This is known as variable shadowing.

Common Mistakes to Avoid πŸš¨β€‹

Mistake 1: Forgetting to Declare​

// ❌ Wrong - Creates global variable (bad!)
score = 100;

// βœ… Right - Always declare with const or let
let score = 100;

Mistake 2: Using let in Reassignment​

let count = 5;

// ❌ Wrong - Don't use 'let' again
let count = 10; // Error!

// βœ… Right - Just reassign without 'let'
count = 10;

Mistake 3: Trying to Reassign const​

const MAX_SIZE = 100;

// ❌ Wrong - Can't reassign const
MAX_SIZE = 200; // Error!

// βœ… Right - Use let if value needs to change
let currentSize = 100;
currentSize = 200; // Works!

Mistake 4: Using Undeclared Variables​

console.log(userName); // ❌ Error! userName not declared

// βœ… Right - Declare first
let userName = "Alice";
console.log(userName); // Works!

Practice Exercise βœοΈβ€‹

Try to predict the output of this code:

const firstName = "John";
let age = 25;
let city = "New York";

// What happens here?
firstName = "Jane"; // 1. Error or OK?
age = 26; // 2. Error or OK?
let age = 30; // 3. Error or OK?
city = "Los Angeles"; // 4. Error or OK?
Click to see answers
  1. ❌ Error - Can't reassign const
  2. βœ… OK - Can reassign let
  3. ❌ Error - Can't redeclare let
  4. βœ… OK - Can reassign let

Key Takeaways πŸŽ―β€‹

βœ… Variables are named containers that store values βœ… Use const by default (prevents reassignment bugs) βœ… Use let when values need to change βœ… Never use var in modern JavaScript βœ… Variable names are case-sensitive βœ… Follow naming conventions (camelCase) βœ… Avoid reserved keywords βœ… Understanding scope helps prevent bugs

Next Steps​

Now that you understand variables, you're ready to learn about Data Types - the different kinds of values you can store in variables!

Conclusion​

In this article, we learned about variables in JavaScriptβ€”the fundamental building blocks for storing data. We learned about the const, let, and var keywords, with clear guidance on when to use each (mostly const and let, never var!). We also learned about variable scope, naming conventions, and common pitfalls to avoid.

Remember: Start with const, use let when needed, and avoid var. Happy coding! πŸš€