Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Variables
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Variables (var, let, const)

Master the foundation of JavaScript programming

Variables are containers that store data values. They're the fundamental building blocks of programming—you'll use them in every program you write. JavaScript gives you three ways to declare variables: var, let, and const. Let's master all three!

What Are Variables?

Think of a variable as a labeled box where you can store a value. You give the box a name, put something in it, and then you can use that name to retrieve or change what's inside.

JAVASCRIPT
// Creating a variable is like labeling a box
let userName = "John";

// The box (userName) now contains "John"
// You can look inside the box anytime
console.log(userName);  // Output: John

// You can change what's in the box
userName = "Jane";
console.log(userName);  // Output: Jane

Why Use Variables?

  • Store data: Keep values for later use
  • Reuse values: Use the same value multiple times
  • Make code readable: Names explain what data means
  • Enable calculations: Perform operations on stored values
  • Track changes: Update values as your program runs

Declaring Variables

In JavaScript, you declare (create) a variable using one of three keywords: let, const, or var.

The Modern Way: let and const

Modern JavaScript (ES6+) uses let and const. These are what you should use in all new code.

JAVASCRIPT
// Using let - for values that can change
let age = 25;
let city = "New York";

// Using const - for values that won't change
const PI = 3.14159;
const birthYear = 1995;

The Old Way: var

var is the original way to declare variables in JavaScript. While it still works, it has quirks that can cause bugs, so we use let and const instead.

JAVASCRIPT
// Old way - don't use this in new code
var oldVariable = "This is outdated";

// Modern way - use this instead
let newVariable = "This is better";

Best Practice: Always use const by default. Only use let when you know you'll need to reassign the variable. Never use var in new code.

Understanding 'let'

let declares a variable that can be reassigned. Use it when you know the value will change.

Basic let Usage

JAVASCRIPT
// Declare and initialize
let score = 0;
console.log(score);  // 0

// Reassign (change the value)
score = 10;
console.log(score);  // 10

// Reassign again
score = score + 5;
console.log(score);  // 15

Declaring Without Initializing

JAVASCRIPT
// Declare without a value
let message;
console.log(message);  // undefined

// Assign later
message = "Hello!";
console.log(message);  // Hello!

let Prevents Redeclaration

JAVASCRIPT
let userName = "John";

// This will cause an error!
let userName = "Jane";  // ❌ SyntaxError: Identifier 'userName' has already been declared

// Instead, just reassign:
userName = "Jane";  // ✅ This works!

Practice with 'let'

Experiment with declaring and reassigning variables

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Understanding 'const'

const declares a constant—a variable that cannot be reassigned. Use it for values that should never change.

Basic const Usage

JAVASCRIPT
// Must initialize when declaring
const PI = 3.14159;
const MAX_USERS = 100;
const API_KEY = "abc123xyz";

console.log(PI);  // 3.14159

const Cannot Be Reassigned

JAVASCRIPT
const birthYear = 1990;

// This will cause an error!
birthYear = 1995;  // ❌ TypeError: Assignment to constant variable

// const also can't be declared without a value
const age;  // ❌ SyntaxError: Missing initializer in const declaration

When to Use const

  • Mathematical constants (PI, e, etc.)
  • Configuration values that don't change
  • Values you want to protect from accidental changes
  • As your default choice (promotes safer, more predictable code)
JAVASCRIPT
// Good uses of const
const DAYS_IN_WEEK = 7;
const COMPANY_NAME = "Falytom";
const MAX_LOGIN_ATTEMPTS = 3;

// Use const for values that won't change
const firstName = "John";
const birthDate = "1990-05-15";

// Even if you perform calculations
const currentYear = 2024;
const birthYear = 1995;
const age = currentYear - birthYear;  // const because we won't change it

Important Note About Objects and Arrays:

With const, you can't reassign the variable, but you can modify the contents of objects and arrays. We'll cover this in detail in later lessons.

JAVASCRIPT
// This is allowed:
const colors = ["red", "blue"];
colors.push("green");  // ✅ Modifying array contents is OK
console.log(colors);   // ["red", "blue", "green"]

// This is NOT allowed:
colors = ["yellow"];   // ❌ Cannot reassign the variable

Practice with 'const'

Work with constants that can't be reassigned

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Understanding 'var' (The Old Way)

var was the only way to declare variables before ES6 (2015). While it still works, it has confusing behaviors that make bugs more likely.

Problems with var

1. var Can Be Redeclared

JAVASCRIPT
var age = 25;
console.log(age);  // 25

// You can redeclare (this is confusing!)
var age = 30;
console.log(age);  // 30

// With let, this would be an error (which is good!)
let score = 10;
let score = 20;  // ❌ Error: already declared

2. var Has Function Scope (Not Block Scope)

JAVASCRIPT
// var ignores block scope
if (true) {
  var x = 10;
}
console.log(x);  // 10 - accessible outside the block!

// let respects block scope
if (true) {
  let y = 10;
}
console.log(y);  // ❌ Error: y is not defined

3. var Is Hoisted

JAVASCRIPT
// This doesn't error, but prints undefined
console.log(name);  // undefined (not an error!)
var name = "John";

// With let, this would error (which is better!)
console.log(age);   // ❌ Error: Cannot access 'age' before initialization
let age = 25;

Don't Use var: Always use let or const in modern JavaScript. The only reason to know about var is so you can understand older code you might see.

See why let is better than var

var (Old & Problematic)

// Old way with var
var userName = "John";
var userAge = 25;

// Can redeclare (bad!)
var userName = "Jane";

// Leaks out of blocks
if (true) {
  var temp = "test";
}
console.log(temp);  // Works (bad!)
Output:
Not run yet...

let (Modern & Safe)

// Modern way with let/const
let userName = "John";
let userAge = 25;

// Cannot redeclare (good!)
// let userName = "Jane";  // Error

// Respects block scope
if (true) {
  let temp = "test";
}
// console.log(temp);  // Error (good!)
Output:
Not run yet...

Variable Naming Rules and Conventions

Rules You MUST Follow

Breaking these will cause errors:

  • Must start with a letter, underscore (_), or dollar sign ($)
  • Can contain letters, digits, underscores, and dollar signs
  • Cannot use reserved words (let, if, for, class, etc.)
  • Are case-sensitive (age and Age are different)
  • Cannot contain spaces or hyphens
JAVASCRIPT
// Valid variable names
let userName = "John";
let user_name = "John";
let _privateName = "John";
let $price = 99.99;
let age2 = 25;

// Invalid variable names (will error)
let 2users = 10;        // ❌ Can't start with number
let user-name = "John"; // ❌ Can't use hyphens
let user name = "John"; // ❌ Can't have spaces
let let = "test";       // ❌ Can't use reserved words

Best Practices (Conventions)

Follow these for clean, professional code:

  • Use camelCase for regular variables (firstName, userAge)
  • Use UPPERCASE for constants (PI, MAX_VALUE)
  • Use descriptive names (age, not a)
  • Start with lowercase letter
  • Avoid single letters except in loops (i, j, k)
  • Use English words (not abbreviations or different languages)
JAVASCRIPT
// Good variable names (descriptive and clear)
let firstName = "John";
let lastName = "Doe";
let userAge = 25;
let isLoggedIn = true;
let totalPrice = 99.99;
let maxAttempts = 3;

// Poor variable names (too short or unclear)
let fn = "John";        // What does 'fn' mean?
let x = 25;             // What is 'x'?
let data = true;        // What kind of data?
let t = 99.99;          // What is 't'?

// Constants (uppercase)
const PI = 3.14159;
const MAX_USERS = 100;
const API_ENDPOINT = "https://api.example.com";

Case Sensitivity

JAVASCRIPT
// JavaScript is case-sensitive - these are all different variables
let name = "John";
let Name = "Jane";
let NAME = "Bob";
let nAmE = "Alice";

console.log(name);  // John
console.log(Name);  // Jane
console.log(NAME);  // Bob
console.log(nAmE);  // Alice

✍️ Naming Convention:

Always stick to camelCase for regular variables: first word lowercase, subsequent words capitalized. This is the JavaScript standard: userName, totalPrice, isActive.

Introduction to Scope

Scope determines where a variable can be accessed in your code. Understanding scope is crucial for writing bug-free code.

Block Scope (let and const)

JAVASCRIPT
// Variables declared with let/const are block-scoped
{
  let blockVariable = "I'm in a block";
  console.log(blockVariable);  // ✅ Works
}

console.log(blockVariable);  // ❌ Error: not defined

// Common with if statements
if (true) {
  let message = "Hello";
  console.log(message);  // ✅ Works inside block
}
console.log(message);  // ❌ Error: not accessible outside

Function Scope

JAVASCRIPT
function greet() {
  let name = "John";
  console.log(name);  // ✅ Works inside function
}

greet();
console.log(name);  // ❌ Error: not defined outside function

Global Scope

JAVASCRIPT
// Variable declared outside any block or function
let globalVariable = "I'm global";

function test() {
  console.log(globalVariable);  // ✅ Accessible everywhere
}

test();
console.log(globalVariable);  // ✅ Also works here

Variable Scope Visualization

See how scope affects variable accessibility

Global Scopeglobal
globalVar="accessible everywhere"
Function Scopefunction
functionVar="only in function"
globalVar="accessible everywhere"
Block Scopeblock
blockVar="only in block"
functionVar="only in function"
Not accessible
globalVar="accessible everywhere"
💡 Remember: Inner scopes can access variables from outer scopes, but outer scopes cannot access variables from inner scopes.

Remember: Variables declared inside a block or function are only accessible within that block or function. Variables declared outside are accessible everywhere.

Choosing Between let and const

Use const When:

  • The value won't be reassigned
  • You want to prevent accidental changes
  • Declaring constants (PI, MAX_VALUE, etc.)
  • You're not sure (const is the safer default)

Use let When:

  • The value will change (counters, accumulators)
  • You're reassigning in a loop
  • The variable's value is calculated over time
JAVASCRIPT
// Use const for values that don't change
const userName = "John";
const birthYear = 1990;
const PI = 3.14159;

// Use let for values that will change
let count = 0;
count = count + 1;
count = count + 1;

let score = 0;
score = score + 10;

let temperature = 72;
temperature = temperature + 5;

// Start with const, change to let if needed
const maxAttempts = 3;     // Won't change
let currentAttempt = 0;    // Will increment

🎯 Pro Tip:

Always start with const. If you later realize you need to reassign the variable, change it to let. This makes your code safer and more predictable.

Common Mistakes with Variables

1. Forgetting to Declare Variables

JAVASCRIPT
// Without strict mode, this creates a global variable (bad!)
userName = "John";  // ❌ No let/const/var

// Always declare your variables
let userName = "John";  // ✅ Correct

2. Trying to Reassign const

JAVASCRIPT
const age = 25;
age = 26;  // ❌ TypeError: Assignment to constant variable

// Use let if you need to reassign
let age = 25;
age = 26;  // ✅ Works

3. Using Variables Before Declaration

JAVASCRIPT
console.log(name);  // ❌ Error with let/const
let name = "John";

// Always declare before using
let name = "John";
console.log(name);  // ✅ Works

4. Confusing Variable Scope

JAVASCRIPT
if (true) {
  let message = "Hello";
}
console.log(message);  // ❌ Error: message not defined

// Fix: Declare outside if needed elsewhere
let message;
if (true) {
  message = "Hello";
}
console.log(message);  // ✅ Works

Practical Examples

Example 1: User Profile

JAVASCRIPT
// User data that won't change
const userId = "user123";
const accountCreated = "2024-01-15";

// User data that might change
let userName = "John Doe";
let email = "john@example.com";
let isVerified = false;

console.log(`User: ${userName}`);
console.log(`Email: ${email}`);
console.log(`Verified: ${isVerified}`);

// Update changeable data
userName = "John Smith";
isVerified = true;

console.log(`Updated user: ${userName}`);
console.log(`Now verified: ${isVerified}`);

Example 2: Shopping Cart

JAVASCRIPT
// Constants
const TAX_RATE = 0.08;
const SHIPPING_COST = 5.99;

// Variables that change
let itemPrice = 29.99;
let quantity = 2;

// Calculate totals
let subtotal = itemPrice * quantity;
let tax = subtotal * TAX_RATE;
let total = subtotal + tax + SHIPPING_COST;

console.log(`Subtotal: $${subtotal}`);
console.log(`Tax: $${tax.toFixed(2)}`);
console.log(`Shipping: $${SHIPPING_COST}`);
console.log(`Total: $${total.toFixed(2)}`);

Shopping Calculator

Practice with const and let in a real scenario

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • Variables store data values that can be used throughout your code
  • Use const for values that won't be reassigned (default choice)
  • Use let for values that will change
  • Never use var in modern JavaScript
  • const must be initialized when declared
  • let and const are block-scoped
  • Variable names should be descriptive and use camelCase
  • Variables are case-sensitive
  • Always declare variables before using them
  • Scope determines where a variable can be accessed

What's Next?

You now understand how to create and use variables in JavaScript! Variables are the foundation—you'll use them in every single program you write from now on.

In the next lesson, we'll explore Data Types—the different kinds of values you can store in variables. You'll learn about numbers, strings, booleans, and more, and how to check what type of data you're working with.

💪 Practice Challenge:

Before moving on, try this:

  1. Create variables for your name, age, city, and favorite hobby
  2. Use const for values that won't change, let for values that might
  3. Print a sentence using all your variables with template literals
  4. Create a simple calculator that stores two numbers and calculates their sum, difference, product, and quotient

Test Your Understanding

Question 1 / 4

Which keyword should you use for a value that won't change?

// Store PI value
____ pi = 3.14159;
Score: 0 / 0

Mastering JavaScript variables! 📦

Previous
Developer Console and Debugging Basics
Next
Data Types and Type Checking

Continue Your JavaScript Journey

Join 2,000+ developers learning JavaScript fundamentals. Get new lessons every week - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo