1. What JavaScript Actually Does โ The Big Picture
Imagine building a house. You need three different teams:
- Architects (HTML) draw the blueprint โ where the walls go, where the doors are, how many rooms exist. HTML defines the structure of your page: headings, paragraphs, images, buttons.
- Interior Designers (CSS) pick the paint colors, furniture, and lighting. CSS defines how your page looks: colors, fonts, spacing, layout.
- Electricians & Plumbers (JavaScript) wire everything so the lights turn on when you flip a switch, the doorbell rings when pressed, water flows when you turn the tap. JavaScript defines what happens when users interact with your page.
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
- Create two files in the same folder:
index.htmlandscript.js - Write the HTML โ notice the
<script>tag at the very end of the<body>:
<!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.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:
// This is a comment โ the computer completely ignores it.
// Comments are notes for YOU, the human reader.
console.log("Hello, world!");
// is a comment. The browser ignores it completely. Use comments to explain why your code does something โ your future self will thank you.
โข
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
- The browser reads your HTML file from top to bottom
- It sees
<h1>Hello World</h1>and draws that text on screen - It reaches
<script src="script.js">โ it pauses, fetchesscript.js, and runs it console.log("Hello, world!")runs โ the message appears in the DevTools Console- 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.
Figure 2 โ The write โ save โ refresh โ check loop. You'll repeat this cycle hundreds of times a day.
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>:
- Browser reads
<head> - Browser finds
<script>โ stops, runs JavaScript - JavaScript tries to find
<h1>โ but the<body>hasn't been read yet! - ๐ฅ JavaScript can't find anything โ your code breaks silently
If you put the script at the end of the body:
- Browser reads ALL the HTML first โ headings, paragraphs, buttons all exist
- Browser reaches
<script>โ runs JavaScript - 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.
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.
let name = "Altamash"; // I can change this later
const birthYear = 2005; // I can NEVER change this
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 is clear. x would be confusing. myAge is good. q is bad.
Altamash is another variable name.
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) |
// ===== 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:
- Reserves a small slot in memory
- Labels that slot "birthYear"
- Puts the number
2005into it - 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
- 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,returnare taken - Be descriptive:
userAgebeatsx.totalPricebeatstp - JavaScript is case-sensitive:
name,Name, andNAMEare three different variables!
// โ
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
Text. Always wrapped in quotes. Can be 'single', "double", or `backtick`.
Number
Any numeric value โ whole numbers and decimals. NO quotes!
Boolean
A yes/no switch. Only two possible values. Powers all decisions.
Null
"Nothing here" โ you set it intentionally to say "this is empty on purpose."
Undefined
A variable that exists but hasn't been given a value yet.
4.1 Let's See Each Type in Detail
// ===== 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:
// 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)
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
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:
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.
Esc, next to 1. On many keyboards it shares a key with ~ (tilde).
${} 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.
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:
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!
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:
- Is
"5" + 3giving"53"instead of8? - Add
console.log(typeof "5")โ shows"string" - Now you know: one of your values is a string, not a number!
- Fix: use
Number("5") + 3โ gives8
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.
// ===== 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:
- Addition: when both sides are numbers โ
5 + 3 = 8 - 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:
// ===== 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")
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:
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)
| Operator | Question it Asks | Example | Result |
|---|---|---|---|
> | Is the left side bigger? | 10 > 5 | true |
< | Is the left side smaller? | 3 < 8 | true |
>= | Is left bigger or equal? | 5 >= 5 | true |
<= | Is left smaller or equal? | 7 <= 3 | false |
=== | Are they exactly the same? (value AND type) | 5 === 5 | true |
!== | Are they different? | "5" !== 5 | true |
== vs === โ ALWAYS Use Triple Equals
JavaScript has two "equals" operators:
==(loose equality) โ Converts types before comparing."5" == 5returnstruebecause JavaScript converts the string"5"to the number5first. This causes unexpected bugs.===(strict equality) โ Checks BOTH value AND type."5" === 5returnsfalsebecause 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:
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)
| Operator | Name | English | Rule |
|---|---|---|---|
&& | 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.
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 keyword starts a decision. Think of it as asking a question.
( ). This is the question being asked: "Is temperature greater than 30?" It evaluates to true or false.
{ } runs ONLY if the condition is true. These curly braces are called a code block.
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:
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)
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:
- JavaScript checks the first
ifcondition:score >= 90โ is 85 โฅ 90? No (false). Skip this block. - Move to next
else if:score >= 80โ is 85 โฅ 80? Yes! (true). Run this block. Print "Grade: B". - STOP. Don't check any more conditions. The first match wins.
- 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.
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.
- Change
scoreto different values (95, 72, 55) and run it โ does the grade change correctly? - Try
console.log("hello" - 3)โ what doesNaNmean? - Try
console.log(typeof null)โ you'll see the famous bug - Create your own variable with your city name and log it with a template literal
- Try
console.log(Boolean(0))andconsole.log(Boolean(""))โ what are "falsy" values?
14. Test Your Knowledge
Quiz: JavaScript Foundations (10 Questions)
const is the default โ it prevents accidental reassignment. Use let only when the value must change. Never use var.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).<body>, all HTML elements already exist, so your JavaScript can find and manipulate them."404"?"404" is text."404" is a string (text). 404 without quotes would be a number. They behave completely differently with the + operator."5" + 3 evaluate to?+ 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".${variable} inside backticks: `Hello ${name}`${expression} โ dollar sign + curly braces โ inside backtick strings.console.log() do?console.log() outputs to the DevTools Console panel. Press F12 to see it. It's for developers, not users.=== (triple equals) check?=== (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 ==.&& (AND) operator require?&& (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)."hello".toUpperCase() return?const upper = name.toUpperCase();if / else if / else chain, how many branches run?true runs, then JavaScript skips all remaining branches. Only one wins.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!
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
- Create a new file called
practices/lesson9-profile.js - Link it at the end of your portfolio's
<body>:lesson8-portfolio.html โ add this line<script src="lesson9-profile.js"></script> - 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; - 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); - Add a placeholder in your HTML:
lesson8-portfolio.html โ add this where you want the card
<div id="profile"></div> - 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; - 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
- Data: You stored information in variables (
firstName,focus, etc.) - Template: You built an HTML string using a template literal with
${} - 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.
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.