Phase 3 โ€” JavaScript
Lesson 0009 โ€ข Beginner โ€ข Deep Dive Edition

JavaScript Foundations

For 8 lessons, you've built pages that look beautiful but sit still. JavaScript is what makes a page live โ€” it reacts to clicks, validates forms, fetches data, and updates the screen without a full reload. This lesson is the doorway into the language that powers React, Next.js, and the entire modern web you're aiming to build.

This is the deep dive edition. Every concept is broken down step-by-step with real-world analogies, line-by-line explanations, and "what's happening inside the computer" sections. Take your time. (MDN: JavaScript)

1. What JavaScript Actually Does โ€” The Big Picture

Imagine building a house. You need three different teams:

HTML Structure (skeleton) CSS Presentation (skin) JavaScript Behavior (brain) what's on the page how it looks what it does Your Page in the Browser layout + style + interactivity

Figure 1 โ€” Three languages, three jobs. The browser combines all three into the final page.

Why JavaScript is the "Brain"

Without JavaScript, your page is like a poster on a wall โ€” you can look at it, but you can't interact with it. JavaScript makes it a living application:

  • It can read the HTML (find a button, read an input field)
  • It can create new HTML elements on the fly
  • It can change CSS styles (make something bigger, change colors)
  • It can react to what the user does (clicks, typing, scrolling)
  • It can fetch data from servers without reloading the page

It runs inside the browser, line by line, top to bottom โ€” which is why we call it a scripting language. No compilation step needed: you write it, the browser runs it.

Where You'll Use This

Every single modern website uses JavaScript. When you search on Google โ€” JS. When you scroll Instagram โ€” JS. When you add items to a cart on Amazon โ€” JS. React, Next.js, Vue, Angular โ€” they're all JavaScript underneath. This lesson is the foundation of everything you'll build for the rest of your career.

2. Your First JavaScript โ€” Step by Step

To run JavaScript, you attach it to an HTML page with the <script> tag. Let's do this together, one step at a time.

๐Ÿชœ Step-by-Step: Running Your First JS Code

  1. Create two files in the same folder: index.html and script.js
  2. Write the HTML โ€” notice the <script> tag at the very end of the <body>:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My First JS</title>
</head>
<body>
  <h1>Hello World</h1>

  <!-- THE SCRIPT TAG GOES HERE, at the END of body -->
  <script src="script.js"></script>
</body>
</html>
<script src="script.js"></script> This tells the browser: "Go find a file called script.js in the same folder, load it, and run the JavaScript code inside it." The src attribute is the file path โ€” just like href in a <link> tag for CSS.

Now write the JavaScript:

script.js
// This is a comment โ€” the computer completely ignores it.
// Comments are notes for YOU, the human reader.

console.log("Hello, world!");
// This is a comment Any line starting with // is a comment. The browser ignores it completely. Use comments to explain why your code does something โ€” your future self will thank you.
console.log("Hello, world!"); This is an instruction (also called a "statement"). Let's break it down piece by piece:
โ€ข console โ€” refers to the browser's built-in console panel (a developer tool)
โ€ข .log() โ€” a command that means "print this message"
โ€ข "Hello, world!" โ€” the text you want to print (in quotes because it's a string)
โ€ข ; โ€” the semicolon marks the end of this instruction, like a period at the end of a sentence

What Happens When You Open This Page

  1. The browser reads your HTML file from top to bottom
  2. It sees <h1>Hello World</h1> and draws that text on screen
  3. It reaches <script src="script.js"> โ€” it pauses, fetches script.js, and runs it
  4. console.log("Hello, world!") runs โ€” the message appears in the DevTools Console
  5. The browser finishes. You see "Hello World" on the page, and "Hello, world!" in the Console

To see the Console: Press F12 on your keyboard (or right-click โ†’ Inspect), then click the Console tab. This is where JavaScript talks back to you.

1. Write script.js 2. Save Ctrl + S 3. Refresh F5 in browser 4. See Output F12 โ†’ Console

Figure 2 โ€” The write โ†’ save โ†’ refresh โ†’ check loop. You'll repeat this cycle hundreds of times a day.

โš ๏ธ WHY the script goes at the end of the body โ€” this is critical

The browser reads your HTML from top to bottom, like reading a book. When it hits a <script> tag, it stops everything, downloads and runs the JavaScript, then continues with the HTML.

If you put the script in the <head>:

  1. Browser reads <head>
  2. Browser finds <script> โ€” stops, runs JavaScript
  3. JavaScript tries to find <h1> โ€” but the <body> hasn't been read yet!
  4. ๐Ÿ’ฅ JavaScript can't find anything โ€” your code breaks silently

If you put the script at the end of the body:

  1. Browser reads ALL the HTML first โ€” headings, paragraphs, buttons all exist
  2. Browser reaches <script> โ€” runs JavaScript
  3. JavaScript can find and manipulate every element โœ…

Rule: Always put <script> right before </body>.

3. Variables โ€” Storing Information (The Box Analogy)

Think about moving to a new house. You have a bunch of boxes, and you label each one so you know what's inside: "Kitchen Stuff", "Books", "Clothes". A variable in JavaScript is exactly the same thing โ€” it's a labeled box that holds a piece of information.

name "Altamash"
age 20
isStudent true

Each box has two parts: the label (the variable name) and the contents (the value). You create a variable using one of two keywords: let or const.

script.js
let name = "Altamash";     // I can change this later
const birthYear = 2005;   // I can NEVER change this
let The keyword. This tells JavaScript: "I'm about to create a new variable." let specifically means "this variable's value might change later." Think of it as a box with a removable lid โ€” you can swap out what's inside.
name The variable name. This is the label on the box. YOU choose this name. It should describe what's inside. name is clear. x would be confusing. myAge is good. q is bad.
= The assignment operator. This does NOT mean "equals" in the math sense. It means "put this value INTO that box." Read it as: "name gets the value Altamash."
"Altamash" The value. This is what goes inside the box. The quotes around it tell JavaScript this is text (a "string"). Without quotes, JavaScript would think Altamash is another variable name.
; The semicolon. Marks the end of this instruction. Like a period at the end of a sentence. JavaScript can sometimes work without it, but always include it โ€” it prevents subtle bugs.
let age = 25; keyword name assign value Keyword let = changeable Name you pick this Value the data stored

Figure 3 โ€” Anatomy of a variable declaration: keyword + name + = + value + semicolon.

3.1 let vs const โ€” When to Use Which

This is one of the most important decisions you'll make hundreds of times a day:

Keyword Meaning Analogy When to Use
const โœ… Value cannot be changed after creation A box sealed with tape โ€” you can look inside but can't swap the contents Default choice. Use this for most things: names, URLs, config values, math results.
let Value can be changed later A box with a lid โ€” you can take things out and put new things in Counters, scores, anything that needs to update: let score = 0; score = 10;
var โŒ The old way (pre-2015) A box with no label that floats around the house โ€” chaotic Never use this. It has weird behavior (hoisting, function scope) that causes bugs. (MDN explains why)
script.js โ€” let vs const in action
// ===== const: the value is LOCKED =====
const birthYear = 2005;
console.log(birthYear);     // โ†’ 2005

// birthYear = 2006;           // โŒ CRASH! TypeError: Assignment to constant variable
// You physically cannot change a const. JavaScript stops and shows an error.

// ===== let: the value can be UPDATED =====
let score = 0;
console.log(score);          // โ†’ 0

score = 10;                   // โœ… This is fine โ€” let allows it
console.log(score);          // โ†’ 10

score = score + 5;           // โœ… Take the old value (10), add 5, store 15
console.log(score);          // โ†’ 15

What Happens in Computer Memory

When you write const birthYear = 2005;, the computer:

  1. Reserves a small slot in memory
  2. Labels that slot "birthYear"
  3. Puts the number 2005 into it
  4. Locks the slot so nobody can overwrite it

When you write let score = 0; then later score = 10;, the computer replaces 0 with 10 in the same slot. The label "score" still points to the same slot, but the contents changed.

Common Mistake: Forgetting that = is NOT "equals"

In math class, x = 5 means "x is equal to 5." In JavaScript, x = 5 means "put 5 into the box called x." This is called assignment, not comparison. We'll learn the real "equals" operator (===) later in this lesson.

So when you see score = score + 5, don't read it as an equation (that makes no sense in math!). Read it as: "Take the current value of score, add 5 to it, and put the result back into score."

3.2 Naming Rules โ€” What You Can and Can't Name a Variable

๐Ÿ’ก Variable Naming Rules
  • Use camelCase: start lowercase, capitalize each new word: firstName, userScore, isLoggedIn
  • Can contain: letters, digits, $, _
  • Can NOT start with a digit: 1name โŒ, name1 โœ…
  • Can NOT use reserved words: let, const, if, return are taken
  • Be descriptive: userAge beats x. totalPrice beats tp
  • JavaScript is case-sensitive: name, Name, and NAME are three different variables!
Good vs Bad Names
// โœ… Good names โ€” descriptive, camelCase
const firstName = "Altamash";
const userAge = 20;
const isLoggedIn = true;
let totalPrice = 499.99;

// โŒ Bad names โ€” avoid these
// let x = "Altamash";         // What is "x"? Nobody knows
// let first_name = "Al";      // Use camelCase, not snake_case
// let 2cool = "yes";           // Can't start with a number
// let let = "hello";           // "let" is a reserved word

4. Data Types โ€” The 5 Kinds of Values

Every value in JavaScript has a type. Think of it like this: when you label your moving boxes, you also know what kind of stuff is inside โ€” "fragile dishes" vs "heavy books" vs "light clothes." Different types of stuff need different handling. JavaScript has 5 basic types you'll use every day:

String

"Hello"

Text. Always wrapped in quotes. Can be 'single', "double", or `backtick`.

Number

42, 3.14

Any numeric value โ€” whole numbers and decimals. NO quotes!

Boolean

true / false

A yes/no switch. Only two possible values. Powers all decisions.

Null

null

"Nothing here" โ€” you set it intentionally to say "this is empty on purpose."

Undefined

undefined

A variable that exists but hasn't been given a value yet.

4.1 Let's See Each Type in Detail

script.js โ€” All 5 types
// ===== STRING: Text data =====
const greeting = "Hello, Altamash!";  // double quotes
const city = 'Delhi';               // single quotes (same thing)
const message = `Welcome back`;      // backtick quotes (special โ€” we'll explain)

// ===== NUMBER: Numeric data =====
const age = 20;                     // whole number (integer)
const price = 99.99;               // decimal number (float)
const temperature = -5;             // negative number

// ===== BOOLEAN: true or false =====
const isLoggedIn = true;            // yes, the user is logged in
const hasPermission = false;        // no, they don't have permission

// ===== NULL: intentionally empty =====
let selectedUser = null;            // no user selected yet (on purpose)

// ===== UNDEFINED: not yet assigned =====
let middleName;                     // declared but no value given
console.log(middleName);           // โ†’ undefined

null vs undefined โ€” What's the Difference?

This confuses everyone at first. Here's the simple way to think about it:

  • null = You deliberately set it to "nothing." Like putting a label on an empty box that says "intentionally left empty." Example: let user = null; means "there's no user selected right now, and I know that."
  • undefined = JavaScript automatically set it because you forgot to give it a value. Like a box that exists but nobody put anything in it yet. Example: let x; โ€” you made the box but didn't fill it.

In practice: Use null when you want to say "empty on purpose." Never intentionally set something to undefined โ€” that's JavaScript's job.

โšก THE TRAP: Strings vs Numbers โ€” THE Most Common Bug

This will bite you. Guaranteed. Read this carefully:

  • "25" โ€” This is a STRING. It's text that happens to look like a number. The quotes make it text.
  • 25 โ€” This is a NUMBER. No quotes. JavaScript treats it as math.

They behave completely differently:

The String vs Number Trap
// NUMBERS: math works normally
console.log(25 + 25);       // โ†’ 50    (addition)

// STRINGS: + glues them together (concatenation)
console.log("25" + "25");   // โ†’ "2525" (joined like text, NOT math!)

// This is WHERE bugs happen.
// You THINK you're adding numbers, but one is a string โ†’ you get text joining.
// This happens constantly when reading from input fields (forms always give strings).

You don't declare the type when you create a variable โ€” JavaScript figures it out from the value. That's why it's called dynamically typed. In other languages (like TypeScript, which you'll learn later), you must declare types explicitly. (MDN: JavaScript data types)

5. Operators โ€” Doing Things With Values

An operator is a symbol that performs an action on values. You already know some from math class. JavaScript has the same ones, plus a few extras.

5.1 Arithmetic Operators (Math)

script.js โ€” Math operators
console.log(5 + 3);    // โ†’ 8    Addition
console.log(10 - 4);   // โ†’ 6    Subtraction
console.log(6 * 7);    // โ†’ 42   Multiplication
console.log(20 / 4);   // โ†’ 5    Division
console.log(17 % 5);   // โ†’ 2    Remainder (modulo)
console.log(2 ** 3);   // โ†’ 8    Exponent (2 to the power of 3)

What is % (Modulo / Remainder)?

This one confuses beginners. 17 % 5 means "divide 17 by 5 and give me the remainder." 17 รท 5 = 3 remainder 2. So 17 % 5 = 2.

Why is this useful?

  • Check if a number is even: number % 2 === 0 โ†’ it's even
  • Check if a number is odd: number % 2 === 1 โ†’ it's odd
  • Wrap around values (like a clock): hours go 1โ†’2โ†’...โ†’12โ†’1โ†’2

5.2 Using Operators with Variables

script.js โ€” Real example
const pricePerItem = 299;
const quantity = 3;
const subtotal = pricePerItem * quantity;   // 299 * 3 = 897
const tax = subtotal * 0.18;                // 18% GST = 161.46
const total = subtotal + tax;                // 897 + 161.46 = 1058.46

console.log(subtotal);  // โ†’ 897
console.log(tax);       // โ†’ 161.46
console.log(total);     // โ†’ 1058.46

This is Real Code

This is exactly how an e-commerce site calculates prices. Store the price and quantity in variables, multiply them, calculate tax, add it up. Every shopping cart you've ever used runs code like this.

6. Template Literals โ€” Building Text with Variables

You'll constantly need to combine text and variables. There are two ways to do this:

script.js โ€” Old way vs New way
const name = "Altamash";
const age = 20;

// โŒ OLD WAY: String concatenation (messy, error-prone)
console.log("Hi, I'm " + name + " and I'm " + age + " years old.");
// You have to manually add spaces, track quotes... it's painful

// โœ… NEW WAY: Template literal (clean, readable)
console.log(`Hi, I'm ${name} and I'm ${age} years old.`);
// Reads like plain English! Variables drop right in.
` ` (backticks) Template literals use backticks, not regular quotes. The backtick key is usually at the top-left of your keyboard, below Esc, next to 1. On many keyboards it shares a key with ~ (tilde).
${name} The ${} is called an interpolation placeholder. Whatever variable or expression you put inside the curly braces gets replaced with its value. So ${name} becomes "Altamash" and ${age} becomes 20.
You can put EXPRESSIONS inside ${}
const price = 200;
const qty = 3;

// You can do math inside ${} !
console.log(`Total: โ‚น${price * qty}`);
// โ†’ "Total: โ‚น600"

// Multi-line text โ€” template literals can span multiple lines
const card = `
  Name: ${name}
  Age:  ${age}
  City: Delhi
`;
console.log(card);
// Prints a nice multi-line text block

Why Template Literals Matter for Your Career

In React and Next.js, you'll build HTML using JavaScript. Template literals are the first step toward that pattern. When you write {`Hello ${user.name}`} in React โ€” that's a template literal! You're learning the foundation right now.

7. Checking Types with typeof โ€” Your First Debugging Tool

When something goes wrong (and it will!), the first question is always: "What type is this value?" The typeof operator answers that instantly:

script.js
console.log(typeof "Hello");      // โ†’ "string"
console.log(typeof 42);           // โ†’ "number"
console.log(typeof true);         // โ†’ "boolean"
console.log(typeof undefined);    // โ†’ "undefined"
console.log(typeof null);         // โ†’ "object"  โš ๏ธ FAMOUS BUG!
โš ๏ธ The typeof null Bug โ€” Yes, It's a Real Bug in JavaScript

typeof null returns "object" instead of "null". This is a mistake from 1995 when JavaScript was created in 10 days. The bug was never fixed because fixing it would break millions of existing websites. Just memorize it: null is NOT an object โ€” it's a special "nothing" value. typeof just reports it incorrectly.

๐Ÿ”ง How to Use typeof for Debugging

When your code does something unexpected, add typeof checks:

  1. Is "5" + 3 giving "53" instead of 8?
  2. Add console.log(typeof "5") โ†’ shows "string"
  3. Now you know: one of your values is a string, not a number!
  4. Fix: use Number("5") + 3 โ†’ gives 8

8. Type Coercion โ€” JavaScript's Silent Bug-Maker

This is the concept that trips up EVERY beginner. Read this section twice.

Type coercion means JavaScript secretly converts one type to another when you mix types. It tries to be "helpful" but often creates bugs.

script.js โ€” Coercion examples
// ===== THE + OPERATOR: The Troublemaker =====
console.log("5" + 3);     // โ†’ "53"   String wins! Number becomes string. Text joined.
console.log(5 + "3");     // โ†’ "53"   Same thing โ€” string on either side = text joining
console.log("Hello" + 5); // โ†’ "Hello5"  Number converted to string, then joined

// ===== THE -, *, / OPERATORS: They Only Do Math =====
console.log("5" - 3);     // โ†’ 2     String "5" converted to number 5, then 5-3=2
console.log("5" * 3);     // โ†’ 15    String "5" โ†’ number 5, then 5*3=15
console.log("10" / 2);    // โ†’ 5     String "10" โ†’ number 10, then 10/2=5

// ===== WHAT HAPPENS WITH NON-NUMERIC STRINGS? =====
console.log("hello" - 3); // โ†’ NaN   "hello" can't become a number โ†’ Not a Number
console.log("hello" * 2); // โ†’ NaN   Same โ€” nonsensical math gives NaN

Why + Is Different From -, *, /

The + operator does two completely different jobs:

  1. Addition: when both sides are numbers โ†’ 5 + 3 = 8
  2. String concatenation: when either side is a string โ†’ "5" + 3 = "53"

When JavaScript sees a string on either side of +, it picks concatenation (text joining). The other operators (-, *, /) ONLY do math โ€” they can't join text โ€” so JavaScript always converts strings to numbers for those.

This is the #1 source of bugs for beginners.

8.1 Explicit Conversion โ€” How Professionals Handle Types

Instead of letting JavaScript guess, you tell it what type you want. This is called explicit conversion:

script.js โ€” Convert types on purpose
// ===== String โ†’ Number =====
const userInput = "42";                    // from a form field (always a string!)
const actualNumber = Number(userInput);    // convert it to a real number
console.log(actualNumber + 8);             // โ†’ 50 (correct math!)
console.log(typeof actualNumber);          // โ†’ "number"

// What happens if the string isn't a valid number?
console.log(Number("hello"));               // โ†’ NaN (Not a Number)
console.log(Number(""));                    // โ†’ 0 (empty string becomes 0)
console.log(Number(true));                 // โ†’ 1 (true = 1, false = 0)

// ===== Number โ†’ String =====
const score = 95;
const scoreText = String(score);          // convert to text
console.log(typeof scoreText);             // โ†’ "string"

// ===== Anything โ†’ Boolean =====
console.log(Boolean(0));                    // โ†’ false (0 is "falsy")
console.log(Boolean(""));                   // โ†’ false (empty string is "falsy")
console.log(Boolean("hello"));              // โ†’ true  (non-empty string is "truthy")
console.log(Boolean(42));                   // โ†’ true  (non-zero number is "truthy")
๐Ÿ’ก Golden Rule: Never Let JavaScript Guess

If you need a number, use Number(). If you need a string, use String(). If you need a boolean, use Boolean(). Explicit conversion makes your intent clear and prevents bugs. This habit will save you hours of debugging.

9. Comparison Operators โ€” Asking Yes/No Questions

Comparisons are how your code asks questions. Every comparison produces a boolean: true or false. Think of them as questions your code asks:

script.js โ€” Comparison operators
const age = 20;

// "Is age greater than 18?"
console.log(age > 18);     // โ†’ true   (20 is greater than 18)

// "Is age less than 18?"
console.log(age < 18);     // โ†’ false  (20 is NOT less than 18)

// "Is age greater than or equal to 20?"
console.log(age >= 20);    // โ†’ true   (20 equals 20, so yes)

// "Is age less than or equal to 19?"
console.log(age <= 19);    // โ†’ false  (20 is NOT less than or equal to 19)

// "Is age EXACTLY equal to 20?" (strict equality)
console.log(age === 20);   // โ†’ true   (same value AND same type)

// "Is age NOT equal to 20?"
console.log(age !== 20);   // โ†’ false  (it IS 20, so "not equal" is false)
OperatorQuestion it AsksExampleResult
>Is the left side bigger?10 > 5true
<Is the left side smaller?3 < 8true
>=Is left bigger or equal?5 >= 5true
<=Is left smaller or equal?7 <= 3false
===Are they exactly the same? (value AND type)5 === 5true
!==Are they different?"5" !== 5true
โš ๏ธ == vs === โ€” ALWAYS Use Triple Equals

JavaScript has two "equals" operators:

  • == (loose equality) โ€” Converts types before comparing. "5" == 5 returns true because JavaScript converts the string "5" to the number 5 first. This causes unexpected bugs.
  • === (strict equality) โ€” Checks BOTH value AND type. "5" === 5 returns false because a string is not a number. No surprises.

Rule: ALWAYS use === and !==. Pretend == doesn't exist. This single rule prevents an entire category of bugs that plague beginners. (MDN: Strict equality)

10. Logical Operators โ€” Combining Conditions

Real-world rules aren't simple. "Can this person enter the club?" isn't just "Are they 18+?" โ€” it's "Are they 18+ AND do they have an ID?" Logical operators let you combine multiple conditions:

script.js โ€” Logical operators
const age = 22;
const hasID = true;
const isBanned = false;

// AND (&&): ALL conditions must be true
// "Is age >= 18 AND does the person have an ID?"
console.log(age >= 18 && hasID);       // โ†’ true  (both are true)
console.log(age >= 18 && !hasID);      // โ†’ false (one is false = whole thing false)

// OR (||): AT LEAST ONE condition must be true
// "Is this person a member OR did they pay at the door?"
const isMember = false;
const paidEntry = true;
console.log(isMember || paidEntry);    // โ†’ true  (paidEntry is true, that's enough)

// NOT (!): Flips true โ†’ false, false โ†’ true
console.log(!true);                     // โ†’ false
console.log(!false);                    // โ†’ true
console.log(!isBanned);                 // โ†’ true  ("is NOT banned" = true)
OperatorNameEnglishRule
&&AND"both must be true"Returns true only if ALL conditions are true
||OR"at least one must be true"Returns true if ANY condition is true
!NOT"flip it"Flips true to false and vice versa

How to Read Complex Conditions

When you see age >= 18 && hasID && !isBanned, read it as English:

"Is age 18 or more, AND does the person have an ID, AND is the person NOT banned?"

All three must be true for the whole thing to be true. If even ONE is false, the whole expression is false.

11. Making Decisions: if / else โ€” Where Code Starts Thinking

Up until now, every line of your code runs no matter what. But real programs need to make decisions. "IF the user is logged in, show the dashboard. ELSE, show the login page." This is called conditional logic โ€” and it's the heart of all programming.

script.js โ€” Simple if/else
const temperature = 35;

if (temperature > 30) {
  console.log("It's hot! Stay hydrated. ๐Ÿฅต");
} else {
  console.log("Nice weather! Go for a walk. ๐Ÿ˜Š");
}
// โ†’ "It's hot! Stay hydrated. ๐Ÿฅต" (because 35 > 30 is true)
if The if keyword starts a decision. Think of it as asking a question.
(temperature > 30) The condition goes inside parentheses ( ). This is the question being asked: "Is temperature greater than 30?" It evaluates to true or false.
{ console.log("It's hot!"); } The code inside the curly braces { } runs ONLY if the condition is true. These curly braces are called a code block.
else { ... } else provides the backup plan. Its code runs ONLY when the if condition is false.

11.1 Multiple Branches with else if

What if you need more than two options? Use else if to add more branches:

script.js โ€” Grade calculator
const score = 85;

if (score >= 90) {
  console.log("Grade: A โ€” Excellent!");
} else if (score >= 80) {
  console.log("Grade: B โ€” Good job!");
} else if (score >= 70) {
  console.log("Grade: C โ€” Keep practicing.");
} else if (score >= 60) {
  console.log("Grade: D โ€” Needs improvement.");
} else {
  console.log("Grade: F โ€” Let's review and retry.");
}
// โ†’ "Grade: B โ€” Good job!" (because 85 >= 80 is the first true condition)
score = 85 score โ‰ฅ 90? false no score โ‰ฅ 80? true! yes "Grade: B" yes "Grade: A"

Figure 4 โ€” The if / else if chain. JavaScript checks top-to-bottom. The first true branch runs; the rest are skipped.

How JavaScript Processes if/else if/else

Think of it like going through airport security checkpoints:

  1. JavaScript checks the first if condition: score >= 90 โ†’ is 85 โ‰ฅ 90? No (false). Skip this block.
  2. Move to next else if: score >= 80 โ†’ is 85 โ‰ฅ 80? Yes! (true). Run this block. Print "Grade: B".
  3. STOP. Don't check any more conditions. The first match wins.
  4. Even though 85 is also โ‰ฅ 70 and โ‰ฅ 60, those checks never happen because we already found a match.

Key insight: Order matters! Put the most specific conditions first (โ‰ฅ 90 before โ‰ฅ 80 before โ‰ฅ 70). If you put โ‰ฅ 60 first, everyone with 60+ would match it and you'd never reach the higher grades.

Common Mistake: Missing curly braces

Always wrap your code in { } โ€” even if it's just one line. Skipping braces is technically allowed but causes bugs when you add more lines later:

// โŒ Dangerous โ€” looks like both lines are in the if, but only the first is:
if (score >= 90)
  console.log("Grade A");
  console.log("Well done!");  // This ALWAYS runs, even for low scores!

// โœ… Safe โ€” curly braces make the scope clear:
if (score >= 90) {
  console.log("Grade A");
  console.log("Well done!");  // Only runs when score >= 90
}

12. Working with Strings โ€” Built-in Tools

Strings come with built-in methods โ€” think of them as tools that come pre-installed. You don't need to build them; JavaScript provides them for free.

script.js โ€” String methods
const name = "Altamash";

// .length โ€” how many characters? (a property, NOT a method)
console.log(name.length);              // โ†’ 8

// .toUpperCase() โ€” convert to ALL CAPS
console.log(name.toUpperCase());      // โ†’ "ALTAMASH"

// .toLowerCase() โ€” convert to all lowercase
console.log(name.toLowerCase());      // โ†’ "altamash"

// .includes() โ€” does this text contain a substring?
console.log(name.includes("tam"));     // โ†’ true
console.log(name.includes("xyz"));     // โ†’ false

// .slice(start, end) โ€” extract a piece of the string
console.log(name.slice(0, 4));        // โ†’ "Alta" (characters 0,1,2,3)
console.log(name.slice(4));           // โ†’ "mash" (from position 4 to the end)

// .trim() โ€” remove spaces from both ends
const messy = "   hello   ";
console.log(messy.trim());            // โ†’ "hello" (spaces gone!)

// .replace() โ€” swap out text
console.log(name.replace("mash", "MASH")); // โ†’ "AltaMASH"

Property vs Method โ€” How to Tell the Difference

  • name.length โ€” Property. No parentheses. It's a stored value โ€” just reading data. "How long is this string?"
  • name.toUpperCase() โ€” Method. Has parentheses (). It does something โ€” it's an action. "Please convert this to uppercase."

The pattern is always: value.property or value.method(). The parentheses tell you: "this is an action."

Strings are Immutable โ€” Methods Don't Change the Original

This is crucial. When you call name.toUpperCase(), it does NOT change name. It creates a brand new string and returns it. The original stays the same:

const name = "Altamash";
name.toUpperCase();       // Creates "ALTAMASH" but we didn't save it!
console.log(name);        // โ†’ still "Altamash" โ€” unchanged!

// To keep the result, save it in a new variable:
const upperName = name.toUpperCase();
console.log(upperName);   // โ†’ "ALTAMASH" โœ…

13. Play With It Right Now

Type code in the editor below, press Run (or Ctrl + Enter), and watch the console output appear. Try breaking things on purpose โ€” errors teach you more than success.


        
๐Ÿ’ก Challenges to Try in the Playground
  1. Change score to different values (95, 72, 55) and run it โ€” does the grade change correctly?
  2. Try console.log("hello" - 3) โ€” what does NaN mean?
  3. Try console.log(typeof null) โ€” you'll see the famous bug
  4. Create your own variable with your city name and log it with a template literal
  5. Try console.log(Boolean(0)) and console.log(Boolean("")) โ€” what are "falsy" values?

14. Test Your Knowledge

Quiz: JavaScript Foundations (10 Questions)

Which keyword should you use by default for most variables?
Correct. const is the default โ€” it prevents accidental reassignment. Use let only when the value must change. Never use var.
Use const by default. It protects your values from being accidentally overwritten. Only switch to let when a value genuinely needs to change (like a counter or score).
Where should you load your external JavaScript file?
Correct. At the end of <body>, all HTML elements already exist, so your JavaScript can find and manipulate them.
Scripts run immediately when the browser reaches them. At the end of the body, all elements are already parsed โ€” your JS can safely find them.
What is the data type of the value "404"?
Correct. Anything in quotes is a string โ€” even if it looks like a number. "404" is text.
The quotes are the clue. "404" is a string (text). 404 without quotes would be a number. They behave completely differently with the + operator.
What does "5" + 3 evaluate to?
Correct. When + sees a string on either side, it switches to text-joining mode. "5" + 3 โ†’ "53" (string concatenation, not math).
+ does double duty: math for numbers, joining for strings. Since "5" is a string, JavaScript converts 3 to "3" and joins them: "53".
How do you embed a variable inside a template literal?
Correct. ${variable} inside backticks: `Hello ${name}`
Template literals use ${expression} โ€” dollar sign + curly braces โ€” inside backtick strings.
What does console.log() do?
Correct. It prints to the browser's Console (F12) โ€” invisible to page visitors. Your #1 debugging tool.
console.log() outputs to the DevTools Console panel. Press F12 to see it. It's for developers, not users.
What does === (triple equals) check?
Correct. === (strict equality) checks both value AND type. "5" === 5 is false because string โ‰  number.
=== is strict equality โ€” it requires both the value and the type to be identical. Always use === instead of ==.
What does the && (AND) operator require?
Correct. && (AND) returns true only when ALL conditions are true. If any is false, the whole thing is false.
&& is AND โ€” every condition must be true. For "at least one true," use || (OR).
What does "hello".toUpperCase() return?
Correct. String methods return a new string โ€” they never change the original. Strings are immutable.
String methods create and return a new string. The original stays unchanged. You must save the result: const upper = name.toUpperCase();
In an if / else if / else chain, how many branches run?
Correct. The first branch whose condition is true runs, then JavaScript skips all remaining branches. Only one wins.
In an if/else-if/else chain, JavaScript checks conditions top to bottom. The FIRST true condition runs, and all remaining branches are skipped.
โ€“

Quiz Complete!

Review any concepts you got wrong using the JavaScript Foundations cheatsheet.

15. Retrieval Practice: Fill In The Blanks

Write from memory. If you can't recall it, that's the point โ€” effortful retrieval is how knowledge sticks. Don't scroll up to check!

/* 1. Which keyword creates a variable that CANNOT be changed? */
 birthYear = 2005;
/* 2. Complete the camelCase variable name */
const  = 2005;
/* 3. A backtick string with ${} is called a _____ literal */
/* 4. Fill in the interpolation placeholder */
const greeting = `Hello, `;
/* 5. Which function prints to the DevTools Console? */
("Hello!");
/* 6. What error do you get when reassigning a const? */
// Assignment to constant โ†’
/* 7. Which equality operator checks BOTH value and type? */
console.log(5 5); // true
/* 8. Which logical operator means "both must be true"? */
console.log(age >= 18 hasID); // AND

16. Build Challenge: Bring Your Portfolio to Life

In Lesson 8 you built practices/lesson8-portfolio.html. Now we'll wire JavaScript into it โ€” the first time your portfolio's content is generated by code, not hand-typed HTML.

๐Ÿชœ Step-by-Step Build Instructions

  1. Create a new file called practices/lesson9-profile.js
  2. Link it at the end of your portfolio's <body>:
    lesson8-portfolio.html โ€” add this line
    <script src="lesson9-profile.js"></script>
  3. In the JS file, create variables that describe YOU:
    lesson9-profile.js
    // Step 1: Store your data in variables
    const firstName = "Altamash";
    const focus = "Full Stack Web Development";
    const projectsBuilt = 8;
    const readyForJS = true;
  4. Build an HTML card using a template literal:
    lesson9-profile.js
    // Step 2: Build HTML with a template literal
    const profileCard = `
      <div class="card">
        <h2>${firstName}</h2>
        <p>Focus: ${focus}</p>
        <p>Projects: ${projectsBuilt}</p>
        <p>JavaScript-ready: ${readyForJS}</p>
      </div>
    `;
    
    // Step 3: Log it first to check
    console.log(profileCard);
  5. Add a placeholder in your HTML:
    lesson8-portfolio.html โ€” add this where you want the card
    <div id="profile"></div>
  6. Inject the card into the page โ€” this is the magic:
    lesson9-profile.js โ€” add this at the bottom
    // Step 4: Put the HTML on the page!
    document.getElementById("profile").innerHTML = profileCard;
  7. Open your portfolio in the browser. The profile card should appear โ€” generated by JavaScript! Open DevTools (F12) โ†’ Console to confirm no errors.

What Just Happened โ€” The data โ†’ template โ†’ inject Pattern

  1. Data: You stored information in variables (firstName, focus, etc.)
  2. Template: You built an HTML string using a template literal with ${}
  3. Inject: You put that HTML into the page using document.getElementById().innerHTML

This exact pattern โ€” data โ†’ template โ†’ inject โ€” is the foundation of EVERY modern framework. React does this. Vue does this. Next.js does this. They just make it more automatic and powerful. But the core idea is what you just built.

โš ๏ธ This Pattern is the Foundation You've just done the single most important thing in DOM scripting. Every React component you'll write in the future is essentially this: take data, build HTML from it, show it on the page. If this pattern makes sense, you're ready for frameworks.
๐Ÿ’ก Stretch goal Make the card respond to a click. Add a button that runs alert("Hi, I'm " + firstName). You don't know the addEventListener syntax yet โ€” try it, get an error, and bring that error to me. Errors are how we learn.

Primary Sources: MDN: Dynamic scripting with JavaScript is the definitive free course. Also javascript.info: JavaScript Fundamentals โ€” the highest-quality beginner JS tutorial online.

Finished the build? Type /teach and show me your portfolio. I'll review your variables, template literals, and the injection pattern. After this, we move on to functions and event handlers โ€” where pages start truly reacting to users.

๐Ÿ’ฌ Questions? Ask your teacher. Variables, data types, operators, comparisons, if/else, template literals, the console โ€” if anything feels fuzzy, ask me now. Better yet: break it in the playground above and paste me the error. This is the most important foundation of Phase 3, so let's make it rock-solid before moving on.