JavaScript Foundations – Variables and Data Types

JavaScript... Lesson 1 of 5 29 min

Welcome to JavaScript

You may have already built pages with HTML and styled them with CSS. Your pages look good — but they just sit there. They don't react, they don't calculate, they don't change. That's about to change.

JavaScript is the programming language of the web. It's the layer that gives web pages a brain — it lets them respond to clicks, process data, update content in real time, validate forms, build games, create charts, and communicate with servers. Every website you interact with dynamically — Gmail, Instagram, Google Maps, Twitter — runs on JavaScript.

The best part? JavaScript runs directly in the browser. You don't need special software to run it — just a text editor and a browser you already have. You can start writing programs today.

Today's Goal: Understand how JavaScript stores and works with information. By the end of this lesson, you'll understand variables, data types, operators, and console.log() — and you'll write your first real JavaScript program that calculates and compares values.

The Three Layers of the Web

Every webpage is built from three languages working together. Think of building a house:

🏗 HTML — The Structure
The raw frame and materials of a house — walls, floors, doors, windows. HTML defines what elements exist on the page: headings, paragraphs, images, buttons, links, forms.

Welcome

Hello, world!

🎨 CSS — The Style
The paint, wallpaper, furniture, and layout. CSS controls how things look: colors, fonts, sizes, spacing, animations, and screen layout.
h1 { color: navy; font-size: 2em; }
button { background: green; color: white; }
⚡ JavaScript — The Behaviour
The electricity, plumbing, and smart home systems. JavaScript makes the page respond, calculate, make decisions, and change over time — without reloading.
let price = 49.99;
let tax = price * 0.08;
let total = price + tax;

How All Three Work Together

HTML
What exists
+
CSS
How it looks
+
JavaScript
What it does
=
A Web App
Fully interactive

What JavaScript Does in the Browser

JavaScript has four core superpowers in the browser. Everything you'll ever build with JS falls into one of these categories:

1. 📝 Change Content Dynamically
JavaScript can read and change anything on the page — headings, paragraphs, images, buttons — without a reload.
// Change the text of an element
document.querySelector('h1').textContent = 'Welcome back, Alice!';

// Change a style
document.querySelector('body').style.background = '#000';
2. 🖱 React to User Events
Every click, keypress, scroll, or mouse hover can trigger JavaScript code to run.
// Run code when user clicks a button
button.addEventListener('click', function() {
    alert('You clicked the button!');
});
3. 🧮 Calculate and Process Data
JavaScript performs arithmetic, text manipulation, date calculations, and logic — acting as the brain of your app.
// Shopping cart calculation
let price = 29.99;
let quantity = 3;
let discount = 10;   // 10% off
let subtotal = price * quantity;
let total = subtotal - (subtotal * discount / 100);
// total = 80.97
4. 🔀 Make Decisions
JavaScript uses conditions to choose different paths — showing different content based on user data, login state, time of day, and more.
// Show different messages based on score
let score = 78;

if (score >= 90) {
    message = "Excellent! Grade: A";
} else if (score >= 70) {
    message = "Good work! Grade: B";
} else {
    message = "Keep practising. Grade: C";
}

How to Link JavaScript to HTML

Like CSS, JavaScript can be added to HTML in three ways. The external file approach is the professional standard and what you should always use for real projects.

Method 1: Inline (Avoid — messy)
Method 2: Internal
Method 3: External file ✅ (Recommended — always use this)

Why at the end of ? HTML is read top to bottom. If you put the

Variables: Storing Information in Memory

At the most fundamental level, programming is about storing information and doing things with it. A variable is a named container for a piece of data. You give it a name, put something inside it, and then refer to that name later whenever you need the data.

Think of Variables Like Labelled Boxes

📦
userName
Contains: "Alice"
📦
age
Contains: 25
📦
isStudent
Contains: true
📦
score
Contains: 87

Each box has a unique label (the variable name) and holds a value. You can look inside, change the contents, or use the value in calculations.

The Three Keywords: let, const, and var

JavaScript gives you three ways to create a variable. You'll use two of them constantly — and mostly avoid the third.

1. let — Use when the value CAN change

let declares a variable whose value can be updated at any point later in the code. Use it for things that change — scores, counters, user input, running totals.

// Declare a variable with let
let score = 0;
console.log(score);  // 0

// Update it later (re-assign)
score = 50;
console.log(score);  // 50

// Update it again
score = score + 10;
console.log(score);  // 60

// Use it in an expression
let bonus = score * 2;
console.log(bonus);  // 120

Step-by-step memory diagram:

let
score
0
→ after score = 50
let
score
50
→ after score + 10
let
score
60

The same box is updated each time — the label stays the same, but the contents change.

2. const — Use when the value should NEVER change

const declares a variable that is locked — you set the value once and it can never be updated. Use it for tax rates, max limits, site names, mathematical constants, API keys, and anything that should stay fixed.

// Declare constants
const TAX_RATE = 0.075;          // 7.5% tax rate
const MAX_LOGIN_ATTEMPTS = 5;
const WEBSITE_NAME = "ShopEasy";
const PI = 3.14159265;

// Use them in calculations
let price = 100;
let taxAmount = price * TAX_RATE;   // 7.5
let totalPrice = price + taxAmount;  // 107.5

// ❌ Trying to change a const causes an ERROR:
TAX_RATE = 0.1;
// TypeError: Assignment to constant variable.
🔒
const TAX_RATE
0.075
Locked forever — safe to rely on
🚫
TAX_RATE = 0.1
ERROR! Can't reassign a const
Convention: Constants that represent fixed settings are often written in UPPER_SNAKE_CASE (all capitals, underscores between words). This makes them visually stand out in code, signalling to every developer reading: "don't change this."

3. var — The old way (avoid in modern code)

var was the only way to declare variables before 2015 (ES6). It works, but it has confusing and bug-prone behaviour around something called scope and hoisting. Modern JavaScript replaced it with let and const.

// Old code you'll see in tutorials and legacy projects:
var userName = "Alice";
var score = 0;

// Modern equivalent (always prefer this):
let score = 0;          // use let if it will change
const userName = "Alice"; // use const if it won't change
Why avoid var? var is function-scoped rather than block-scoped, meaning it can "leak" out of if blocks and loops in unexpected ways, causing hard-to-find bugs. It also gets "hoisted" to the top of its scope, which creates weird situations where you can use a variable before it's declared. You'll still see var in old codebases, so understanding it helps — but don't write it yourself.

Variable Naming Rules and Best Practices

Variable names are case-sensitive and follow specific rules. Getting naming right from the start makes your code far easier to read and debug.

✅ Valid variable names:
let userName = "Alice";     // camelCase — recommended
let user_name = "Alice";   // snake_case — also valid
let _count = 0;            // underscore start — valid
let $price = 29.99;        // dollar sign start — valid
let totalAmount2024 = 0;   // numbers inside name — valid
❌ Invalid variable names (will cause errors):
let 2users = "error";    // ❌ Can't start with a number
let user-name = "error"; // ❌ Hyphens not allowed
let user name = "error"; // ❌ Spaces not allowed
let let = "error";       // ❌ Can't use reserved keywords
let class = "error";     // ❌ 'class' is a reserved keyword

Naming Best Practices: The Guiding Principle is Clarity

❌ Vague / cryptic let x = 25; let a = "Alice"; let n = 49.99; let t = 53.99;
✅ Clear / descriptive let userAge = 25; let firstName = "Alice"; let productPrice = 49.99; let totalWithTax = 53.99;

A good rule: your variable name should tell you what the data represents, without needing a comment to explain it.

Quick Decision Guide — which keyword?
• Does the value ever need to change? → use let
• Is the value fixed forever? → use const
• Is it old code from before 2015? → probably var — understand it but don't copy it

Pro tip: Start everything as const. If you later need to change it, switch to let. This habit prevents many accidental re-assignments.

Data Types: The Different Kinds of Information

Not all data is the same. The number 42 is different from the text "42". You can do maths with the first, but not the second. A yes/no answer is different from both. JavaScript has distinct data types to represent these different kinds of information, and understanding them deeply will prevent many bugs.

JavaScript's Five Primitive Data Types (Most Important)

String
Text
Number
Numeric
Boolean
True/False
Null
Intentional empty
Undefined
Not yet set

1. String — Text Data

A string is any sequence of characters — letters, numbers, symbols, spaces — wrapped in quotation marks. Strings represent words, sentences, names, email addresses, HTML content, or any textual data.

// Strings can use single quotes, double quotes, or backticks
let firstName = "Alice";          // double quotes
let lastName = 'Wonderland';      // single quotes — same thing
let greeting = `Hello, World!`;   // backticks — has special powers

// Strings can hold anything — letters, numbers, symbols
let email = "alice@example.com";
let phone = "0801-234-5678";      // "number" stored as text
let htmlTag = "

Title

"; // Important: these are NOT the same! let numericFive = 5; // a NUMBER — you can do math let textFive = "5"; // a STRING — it's just text console.log(numericFive + 3); // 8 (maths) console.log(textFive + 3); // "53" (text joined together!)

Working with strings — combining and measuring:

// Method 1: Concatenation (joining with +)
let first = "Alice";
let last = "Wonderland";
let fullName = first + " " + last;
console.log(fullName);  // "Alice Wonderland"

// Method 2: Template literals (backticks — recommended)
let age = 25;
let bio = `My name is ${first} and I am ${age} years old.`;
console.log(bio);  // "My name is Alice and I am 25 years old."

// String length
let word = "JavaScript";
console.log(word.length);  // 10 (counts every character)

Template Literals vs Concatenation:

Old way (concatenation):

"Hello, " + name + "! You are " + age + " years old."

Hard to read, error-prone

Modern way (template literal):

`Hello, ${name}! You are ${age} years old.`

Clean, readable, powerful

2. Number — Numeric Data

The number type covers all numeric values — whole numbers, decimals, negatives, and very large or very small values. Unlike many languages, JavaScript doesn't separate integers from decimals; they're all just "number."

// Whole numbers (integers)
let year = 2024;
let population = 8000000000;
let negativeTemp = -15;
let zero = 0;

// Decimal numbers (floats)
let price = 49.99;
let taxRate = 0.075;     // 7.5%
let pi = 3.14159265;
let tiny = 0.0001;

// Numbers without quotes — you can do maths with these
let a = 10;
let b = 3;

console.log(a + b);   // 13   (addition)
console.log(a - b);   // 7    (subtraction)
console.log(a * b);   // 30   (multiplication)
console.log(a / b);   // 3.333... (division)
console.log(a % b);   // 1    (remainder / modulus)
console.log(a ** b);  // 1000 (exponentiation: 10³)

Special numeric values to know:

// NaN — "Not a Number" — result of bad maths
let result = "hello" * 5;
console.log(result);           // NaN
console.log(isNaN(result));    // true

// Infinity — result of dividing by zero
let inf = 1 / 0;
console.log(inf);              // Infinity

// Number.MAX_SAFE_INTEGER — largest safe whole number
console.log(Number.MAX_SAFE_INTEGER);  // 9007199254740991
Important Gotcha — Floating Point Precision:
0.1 + 0.2 in JavaScript equals 0.30000000000000004, not 0.3. This is a quirk of how computers store decimals in binary. When working with money, always round results: parseFloat((0.1 + 0.2).toFixed(2))0.3.

3. Boolean — True or False

A boolean has only two possible values: true or false. They're used to represent yes/no, on/off, logged-in/logged-out states and drive every decision in your program.

// Direct boolean values (no quotes!)
let isLoggedIn = false;
let hasSubscription = true;
let darkMode = false;
let emailVerified = true;
let gameOver = false;

// Booleans from comparisons
let age = 20;
let isAdult = age >= 18;         // true (20 is ≥ 18)
let canDrinkUS = age >= 21;      // false (20 is not ≥ 21)
let isPerfectScore = score === 100; // depends on score

// Common mistake: TRUE vs true
let valid = true;    // ✅ correct — lowercase
let invalid = True;  // ❌ error — JavaScript is case-sensitive!

Booleans power every decision in your app:

// The if statement runs code based on true/false
if (isLoggedIn) {
    console.log("Welcome back!");
} else {
    console.log("Please log in.");
}

// More complex logic with AND (&&) and OR (||)
let age = 25;
let hasID = true;
let canEnter = age >= 18 && hasID;  // both must be true
console.log(canEnter);  // true

Visual: Booleans as switches

🟢
true
ON / YES / active
🔴
false
OFF / NO / inactive

4. Null — Intentionally Empty

null means "this variable intentionally has no value." You set it yourself as a deliberate signal that the variable is empty or that the expected data hasn't been provided yet. Think of it like an empty box you've consciously decided to leave empty.

// null means "no value, intentionally"
let selectedUser = null;     // No user selected yet
let currentMovie = null;     // No movie playing
let searchResult = null;     // Search hasn't been performed

// Later, you assign a real value
selectedUser = "Alice";      // Now a user is selected
currentMovie = "Inception";  // Now a movie is playing

// Useful for representing "not found" states
function findUser(id) {
    if (id === 1) return { name: "Alice" };
    return null;  // Signal: user not found
}

let user = findUser(99);
console.log(user);  // null — not found
📦
currentMovie = null
Deliberately empty — you chose to put nothing here

5. Undefined — Not Yet Assigned

undefined means a variable has been declared but hasn't been given a value yet. JavaScript automatically assigns this value — you rarely set it yourself. It's JavaScript saying: "I know this variable exists, but I don't know what's inside it."

// Declared but not assigned — JavaScript sets it to undefined
let winner;
console.log(winner);  // undefined

// Later, assign a value
winner = "Alice";
console.log(winner);  // "Alice"

// Function parameters not provided are also undefined
function greet(name) {
    console.log(name);
}
greet();  // undefined — no argument was passed
null vs undefined — what's the difference?

undefined: JavaScript says "I don't know what this is" — the variable exists but was never assigned a value.
null: You say "this is deliberately empty" — you consciously set it to indicate the absence of a value.

Think of it like a parking space: undefined means the space doesn't have a sign yet. null means there's a sign saying "EMPTY."

Checking Types with typeof

You can always check what type of data a variable holds using the typeof operator. It returns a string describing the type.

console.log(typeof "Hello");        // "string"
console.log(typeof 42);             // "number"
console.log(typeof 3.14);           // "number"
console.log(typeof true);           // "boolean"
console.log(typeof false);          // "boolean"
console.log(typeof undefined);      // "undefined"
console.log(typeof null);           // "object" ← famous JS quirk!
console.log(typeof "42");           // "string" — it's text, not a number!
The null quirk: typeof null returns "object" — this is a well-known bug in JavaScript from 1995 that has never been fixed to avoid breaking old websites. To check for null, use value === null instead.

Operators: Doing Things With Data

Operators are symbols that perform operations on values. JavaScript has four categories you'll use constantly: arithmetic, assignment, comparison, and logical. Let's go deep into each.

Arithmetic Operators: + − * / % **

These perform mathematical calculations on numbers.

let a = 17;
let b = 5;

// Addition
console.log(a + b);    // 22

// Subtraction
console.log(a - b);    // 12

// Multiplication
console.log(a * b);    // 85

// Division
console.log(a / b);    // 3.4

// Modulus (remainder after division)
console.log(a % b);    // 2  (17 ÷ 5 = 3 remainder 2)

// Exponentiation (power)
console.log(a ** 2);   // 289  (17²)
console.log(2 ** 10);  // 1024 (2¹⁰)

The Modulus (%) Operator — Very Useful!

The modulus gives you the remainder after integer division. This is incredibly useful for checking even/odd numbers, cycling through arrays, and time calculations.

Even/Odd Check:
10 % 2 = 0 → even
7 % 2 = 1 → odd
Minutes from seconds:
185 % 60 = 5
(3 mins, 5 seconds remaining)

Shorthand assignment operators — update a variable in one step:

let score = 100;

score += 10;   // same as: score = score + 10  → 110
score -= 5;    // same as: score = score - 5   → 105
score *= 2;    // same as: score = score * 2   → 210
score /= 3;    // same as: score = score / 3   → 70
score++;       // same as: score = score + 1   → 71
score--;       // same as: score = score - 1   → 70

Comparison Operators: === !== > < >= <=

Comparison operators compare two values and always return a boolean — either true or false. They are the foundation of all logic and decision-making in your programs.

let x = 10;
let y = 20;

// Strict equality (===)  — value AND type must match
console.log(x === 10);    // true
console.log(x === "10");  // false — different types!
console.log(x === y);     // false

// Strict inequality (!==)
console.log(x !== y);     // true
console.log(x !== 10);    // false

// Greater than / Less than
console.log(y > x);       // true   (20 > 10)
console.log(x > y);       // false  (10 > 20)
console.log(x < y);       // true   (10 < 20)

// Greater than or equal / Less than or equal
console.log(x >= 10);     // true   (10 is equal to 10)
console.log(x >= 11);     // false  (10 is less than 11)
console.log(y <= 20);     // true   (20 is equal to 20)
console.log(y <= 19);     // false  (20 is greater than 19)

⚠️ Critical: === vs == — Always use ===

JavaScript has two equality operators. The double equals (==) tries to convert types before comparing (called "loose equality"). This leads to bizarre, bug-causing results. The triple equals (===) is "strict equality" — it checks both value AND type. Always use ===.

// Loose equality == (confusing and dangerous)
console.log(0 == false);   // true  ← bizarre!
console.log("" == false);  // true  ← bizarre!
console.log(1 == "1");     // true  ← converts types
console.log(null == undefined);  // true ← strange

// Strict equality === (predictable and safe)
console.log(0 === false);  // false — different types
console.log("" === false); // false — different types
console.log(1 === "1");    // false — number ≠ string
console.log(null === undefined); // false — different types

Professional JavaScript uses === and !== exclusively. Treat == as non-existent.

Real-world comparison examples:

let age = 22;
let score = 75;
let password = "abc123";
const PASSING_GRADE = 60;

let isAdult = age >= 18;             // true
let canVote = age >= 18;             // true (Nigeria voting age)
let isPassing = score >= PASSING_GRADE; // true (75 ≥ 60)
let isCorrectPassword = password === "abc123"; // true

// Use results in conditions
if (isPassing) {
    console.log("Congratulations, you passed!");
}

Logical Operators: && || !

Logical operators combine or invert boolean values, letting you express more complex conditions.

// AND (&&) — BOTH conditions must be true
let age = 25;
let hasID = true;

let canEnterClub = age >= 18 && hasID;  // true && true = true

// OR (||) — AT LEAST ONE condition must be true
let isWeekend = false;
let isHoliday = true;

let dayOff = isWeekend || isHoliday;    // false || true = true

// NOT (!) — Inverts a boolean
let isOnline = true;
let isOffline = !isOnline;               // !true = false

// Complex combined conditions
let score = 80;
let attendance = 90;
let qualifiesForAward = score >= 75 && attendance >= 85;
// true && true = true

Truth Table — How Logical Operators Work:

A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true

console.log() — Your Window into JavaScript

console.log() is one of the most important tools you'll use as a developer. It prints information from your JavaScript code to the browser's console — a special panel inside developer tools where you can see what your code is doing step by step.

Think of console.log() as JavaScript's way of talking back to you. Your code runs invisibly — but console.log() is like a window that lets you peer inside and see exactly what's happening.

How to Open the Browser Console

Chrome or Edge: Press F12 or right-click → Inspect → click the Console tab
Or shortcut: Ctrl+Shift+J (Windows) or Cmd+Option+J (Mac)
Firefox: Press F12 or right-click → Inspect → click Console
Safari (Mac): Enable developer menu in Preferences → Advanced → tick "Show Develop menu" → Develop → Show JavaScript Console

Everything You Can Do with console.log()

// Log a plain string
console.log("Hello, World!");

// Log a variable
let name = "Alice";
console.log(name);             // Alice

// Log a number
let age = 25;
console.log(age);              // 25

// Log multiple values at once (comma-separated)
console.log("Name:", name, "Age:", age);  // Name: Alice Age: 25

// Log the result of a calculation
let price = 49.99;
let tax = price * 0.075;
console.log("Tax amount:", tax);        // Tax amount: 3.74925

// Log a boolean
let isAdult = age >= 18;
console.log("Is adult:", isAdult);      // Is adult: true

// Log with labels for easy debugging
console.log("--- Debug Info ---");
console.log("price:", price);
console.log("tax:", tax);
console.log("total:", price + tax);

// Other console methods
console.warn("This is a warning!");    // Yellow warning in console
console.error("This is an error!");   // Red error in console

What you'll see in the console:

Hello, World!
Alice
25
Name: Alice Age: 25
Tax amount: 3.74925
Is adult: true
--- Debug Info ---
price: 49.99
tax: 3.74925
total: 53.73925
The Golden Rule of Debugging: When something isn't working right, add console.log() statements everywhere to see what values your variables actually hold. Most bugs come from variables holding unexpected values — and console.log() exposes that immediately. Professional developers use it constantly, not just beginners.

Project Setup: Create Your First JavaScript File

Now you're going to put everything together and write a real JavaScript file. Follow these steps exactly.

Step 1: Create a project folder
Create a folder on your desktop called day1-javascript. Inside it, create two files:
index.html and script.js
Step 2: Write the HTML
Open index.html in your text editor and paste this:



    
    
    Day 1 - JavaScript Foundations


    

Day 1: JavaScript Foundations

Open the browser console (F12) to see the output.

Step 3: Open script.js and start writing
Open script.js in your editor — this is where all your JavaScript goes.
Step 4: Open in browser and check console
Double-click index.html to open it in your browser. Press F12 to open DevTools and click the Console tab. Every time you save script.js and refresh the browser, the console will update.
📁 day1-javascript/
├── 📄 index.html   ← links to script.js
└── ⚡ script.js    ← where you write your code

Practical Exercises: Write Your First Programs

These exercises build progressively. Work through them in your script.js file, check the console after each one, and try to predict the output before you see it.

Exercise 1: Store and Log Different Data Types

Goal: Create one variable of each data type and log it with a descriptive label. Confirm your understanding of how each type is declared.

// Exercise 1: Data Types Explorer
console.log("=== Exercise 1: Data Types ===");

// String
let fullName = "Chukwuemeka Obi";
console.log("Full name:", fullName);
console.log("Type:", typeof fullName);  // "string"

// Number
let birthYear = 1998;
console.log("Birth year:", birthYear);
console.log("Type:", typeof birthYear);  // "number"

// Decimal number
let salary = 250000.50;
console.log("Monthly salary (₦):", salary);

// Boolean
let isEmployed = true;
console.log("Is employed:", isEmployed);
console.log("Type:", typeof isEmployed);  // "boolean"

// Null
let middleName = null;
console.log("Middle name:", middleName);  // null

// Undefined
let nickname;
console.log("Nickname:", nickname);  // undefined

Expected console output:

=== Exercise 1: Data Types ===
Full name: Chukwuemeka Obi
Type: string
Birth year: 1998
Type: number
Monthly salary (₦): 250000.5
Is employed: true
Type: boolean
Middle name: null
Nickname: undefined

Exercise 2: Add Two Numbers Together

Goal: Store two numbers in variables, add them, and display the result clearly in the console. Then change the numbers and check the output updates automatically.

// Exercise 2: Add Two Numbers
console.log("=== Exercise 2: Addition ===");

let firstNumber = 47;
let secondNumber = 38;

let sum = firstNumber + secondNumber;

console.log("First number:", firstNumber);
console.log("Second number:", secondNumber);
console.log("Sum:", sum);
console.log(`${firstNumber} + ${secondNumber} = ${sum}`);

Expected output:

=== Exercise 2: Addition ===
First number: 47
Second number: 38
Sum: 85
47 + 38 = 85

Challenge: Change firstNumber to 100 and secondNumber to 250. What does the console show now?

Exercise 3: All Arithmetic Operations

Goal: Practice all six arithmetic operators on the same pair of numbers and log each result.

// Exercise 3: All Arithmetic Operators
console.log("=== Exercise 3: Arithmetic ===");

let num1 = 24;
let num2 = 7;

console.log(`${num1} + ${num2} = ${num1 + num2}`);   // 31
console.log(`${num1} - ${num2} = ${num1 - num2}`);   // 17
console.log(`${num1} * ${num2} = ${num1 * num2}`);   // 168
console.log(`${num1} / ${num2} = ${num1 / num2}`);   // 3.428...
console.log(`${num1} % ${num2} = ${num1 % num2}`);   // 3
console.log(`${num1} ** 2 = ${num1 ** 2}`);           // 576

// Is num1 even or odd?
let isEven = num1 % 2 === 0;
console.log(`Is ${num1} even?`, isEven);  // true (24 is even)

Expected output:

=== Exercise 3: Arithmetic ===
24 + 7 = 31
24 - 7 = 17
24 * 7 = 168
24 / 7 = 3.4285714285714284
24 % 7 = 3
24 ** 2 = 576
Is 24 even? true

Exercise 4: Compare Two Numbers

Goal: Use every comparison operator on two numbers and log the boolean results. Observe how each one evaluates.

// Exercise 4: Comparison Operators
console.log("=== Exercise 4: Comparisons ===");

let myAge = 23;
let friendAge = 30;

console.log("My age:", myAge);
console.log("Friend's age:", friendAge);
console.log("---");

console.log("myAge === friendAge:", myAge === friendAge);  // false
console.log("myAge !== friendAge:", myAge !== friendAge);  // true
console.log("myAge > friendAge:", myAge > friendAge);      // false
console.log("myAge < friendAge:", myAge < friendAge);      // true
console.log("myAge >= 18:", myAge >= 18);                  // true
console.log("myAge <= 23:", myAge <= 23);                  // true

// Store comparison results in variables
let amIYounger = myAge < friendAge;
let canIDrive = myAge >= 18;
let areSameAge = myAge === friendAge;

console.log("---");
console.log("Am I younger than friend?", amIYounger);  // true
console.log("Can I drive?", canIDrive);                // true
console.log("Same age?", areSameAge);                  // false

Expected output:

=== Exercise 4: Comparisons ===
My age: 23
Friend's age: 30
---
myAge === friendAge: false
myAge !== friendAge: true
myAge > friendAge: false
myAge < friendAge: true
myAge >= 18: true
myAge <= 23: true
---
Am I younger than friend? true
Can I drive? true
Same age? false

Exercise 5: Build a Price Calculator

Goal: Combine variables, arithmetic, and string output to build a real-world calculation. Practice using const for fixed values and let for calculated values.

// Exercise 5: Price Calculator
console.log("=== Exercise 5: Price Calculator ===");

// Constants — things that don't change
const VAT_RATE = 0.075;           // 7.5% VAT
const DELIVERY_FEE = 1500;        // ₦1500 flat rate

// Variables — order details
let productName = "Wireless Headphones";
let unitPrice = 45000;
let quantity = 2;

// Calculations
let subtotal = unitPrice * quantity;
let vatAmount = subtotal * VAT_RATE;
let grandTotal = subtotal + vatAmount + DELIVERY_FEE;

// Display the receipt
console.log("=========================");
console.log("        RECEIPT          ");
console.log("=========================");
console.log("Product:", productName);
console.log("Unit price: ₦" + unitPrice.toLocaleString());
console.log("Quantity:", quantity);
console.log("-------------------------");
console.log("Subtotal: ₦" + subtotal.toLocaleString());
console.log(`VAT (${VAT_RATE * 100}%): ₦${vatAmount.toLocaleString()}`);
console.log("Delivery: ₦" + DELIVERY_FEE.toLocaleString());
console.log("=========================");
console.log("TOTAL: ₦" + grandTotal.toLocaleString());
console.log("=========================");

Expected output:

=== Exercise 5: Price Calculator ===
=========================
        RECEIPT          
=========================
Product: Wireless Headphones
Unit price: ₦45,000
Quantity: 2
-------------------------
Subtotal: ₦90,000
VAT (7.5%): ₦6,750
Delivery: ₦1,500
=========================
TOTAL: ₦98,250
=========================

Try It: Change unitPrice to 12000 and quantity to 5. Does the total recalculate correctly?

Exercise 6: Age & Grade Calculator

Goal: Combine arithmetic and comparisons in a meaningful program. This is where variables and operators work together.

// Exercise 6: Age and Grade Calculator
console.log("=== Exercise 6: Age & Grade ===");

// --- Age Calculator ---
const CURRENT_YEAR = 2024;
let birthYear = 2001;
let age = CURRENT_YEAR - birthYear;

let isAdult = age >= 18;
let canVoteNigeria = age >= 18;
let seniorCitizen = age >= 65;

console.log("Birth year:", birthYear);
console.log("Current age:", age);
console.log("Is adult:", isAdult);
console.log("Can vote:", canVoteNigeria);
console.log("Senior citizen:", seniorCitizen);

console.log("---");

// --- Grade Calculator ---
let mathScore = 78;
let englishScore = 85;
let scienceScore = 72;

let totalScore = mathScore + englishScore + scienceScore;
let averageScore = totalScore / 3;

// Round to 1 decimal place
let roundedAverage = Math.round(averageScore * 10) / 10;

// Grade comparisons
let isDistinction = averageScore >= 70;
let isMeritOrAbove = averageScore >= 60;
let isPassing = averageScore >= 40;

console.log("Math:", mathScore);
console.log("English:", englishScore);
console.log("Science:", scienceScore);
console.log("Total:", totalScore, "/ 300");
console.log("Average:", roundedAverage);
console.log("Distinction (≥70)?", isDistinction);
console.log("Merit (≥60)?", isMeritOrAbove);
console.log("Passing (≥40)?", isPassing);

Expected output:

=== Exercise 6: Age & Grade ===
Birth year: 2001
Current age: 23
Is adult: true
Can vote: true
Senior citizen: false
---
Math: 78
English: 85
Science: 72
Total: 235 / 300
Average: 78.3
Distinction (≥70)? true
Merit (≥60)? true
Passing (≥40)? true

Complete script.js — All Exercises Together

Here's a clean, complete script.js file with all six exercises in one place:

// =============================================
// JavaScript Day 1: Variables & Data Types
// =============================================

// =============================================
// Exercise 1: Data Types
// =============================================
console.log("=== Exercise 1: Data Types ===");

let fullName = "Chukwuemeka Obi";
let birthYear = 1998;
let salary = 250000.50;
let isEmployed = true;
let middleName = null;
let nickname;

console.log("Name:", fullName, "| Type:", typeof fullName);
console.log("Birth year:", birthYear, "| Type:", typeof birthYear);
console.log("Salary:", salary);
console.log("Employed:", isEmployed, "| Type:", typeof isEmployed);
console.log("Middle name:", middleName);
console.log("Nickname:", nickname);
console.log("");

// =============================================
// Exercise 2: Add Two Numbers
// =============================================
console.log("=== Exercise 2: Addition ===");

let firstNumber = 47;
let secondNumber = 38;
let sum = firstNumber + secondNumber;

console.log(`${firstNumber} + ${secondNumber} = ${sum}`);
console.log("");

// =============================================
// Exercise 3: All Arithmetic
// =============================================
console.log("=== Exercise 3: Arithmetic ===");

let num1 = 24;
let num2 = 7;

console.log(`${num1} + ${num2} = ${num1 + num2}`);
console.log(`${num1} - ${num2} = ${num1 - num2}`);
console.log(`${num1} * ${num2} = ${num1 * num2}`);
console.log(`${num1} / ${num2} = ${(num1 / num2).toFixed(4)}`);
console.log(`${num1} % ${num2} = ${num1 % num2}`);
console.log(`${num1}² = ${num1 ** 2}`);
console.log(`Is ${num1} even? ${num1 % 2 === 0}`);
console.log("");

// =============================================
// Exercise 4: Compare Two Numbers
// =============================================
console.log("=== Exercise 4: Comparisons ===");

let myAge = 23;
let friendAge = 30;

console.log("myAge === friendAge:", myAge === friendAge);
console.log("myAge !== friendAge:", myAge !== friendAge);
console.log("myAge > friendAge:", myAge > friendAge);
console.log("myAge < friendAge:", myAge < friendAge);
console.log("myAge >= 18:", myAge >= 18);
console.log("Am I younger?", myAge < friendAge);
console.log("");

// =============================================
// Exercise 5: Price Calculator
// =============================================
console.log("=== Exercise 5: Price Calculator ===");

const VAT_RATE = 0.075;
const DELIVERY_FEE = 1500;

let productName = "Wireless Headphones";
let unitPrice = 45000;
let quantity = 2;

let subtotal = unitPrice * quantity;
let vatAmount = subtotal * VAT_RATE;
let grandTotal = subtotal + vatAmount + DELIVERY_FEE;

console.log("Product:", productName);
console.log("Subtotal: ₦" + subtotal.toLocaleString());
console.log(`VAT (${VAT_RATE * 100}%): ₦${vatAmount.toLocaleString()}`);
console.log("Delivery: ₦" + DELIVERY_FEE.toLocaleString());
console.log("TOTAL: ₦" + grandTotal.toLocaleString());
console.log("");

// =============================================
// Exercise 6: Age & Grade Calculator
// =============================================
console.log("=== Exercise 6: Age & Grade ===");

const CURRENT_YEAR = 2024;
let myBirthYear = 2001;
let myComputedAge = CURRENT_YEAR - myBirthYear;

let mathScore = 78;
let englishScore = 85;
let scienceScore = 72;
let average = (mathScore + englishScore + scienceScore) / 3;

console.log("Age:", myComputedAge);
console.log("Is adult:", myComputedAge >= 18);
console.log("Average score:", Math.round(average * 10) / 10);
console.log("Distinction:", average >= 70);

Day 1 Key Concepts Quick Reference

// ===== VARIABLES =====
let score = 0;          // can change
const TAX = 0.075;      // cannot change (locked)

// ===== DATA TYPES =====
let name = "Alice";       // String — text in quotes
let age = 25;             // Number — no quotes
let isAdult = true;       // Boolean — true or false
let selected = null;      // Null — intentionally empty
let pending;              // Undefined — not yet set

// ===== ARITHMETIC =====
let a = 10, b = 3;
a + b  // 13
a - b  // 7
a * b  // 30
a / b  // 3.333
a % b  // 1 (remainder)
a ** b // 1000 (10³)

// ===== COMPARISONS (always return boolean) =====
a === b  // false (strict equal)
a !== b  // true  (not equal)
a > b    // true
a < b    // false
a >= 10  // true
a <= 9   // false

// ===== CONSOLE.LOG =====
console.log("Label:", value);
console.log(`Name: ${name}, Age: ${age}`);

Day 1 Completion Checklist

□ I can explain what JavaScript does in the browser
□ I know when to use let vs const (and why not var)
□ I can identify all five primitive data types by looking at a value
□ I understand the difference between a number 5 and a string "5"
□ I can use all six arithmetic operators and understand what % does
□ I know to always use === (never ==) for equality checks
□ I can use console.log() to inspect variables with clear labels
□ I completed all 6 exercises and saw the correct console output

Complete this lesson

Mark as complete to track your progress