The building blocks of every JavaScript program — values, variables, expressions, template literals, and functions that accept input and return output
In Chapter 19, you learned what JavaScript is and how it connects to a web page through a linked script file. You ran your first statements, used console.log() to send messages to the browser console, and saw that JavaScript executes line by line, from top to bottom.
Now it is time to learn how JavaScript actually works as a language. Every useful JavaScript program — no matter how small or large — is built from a small set of foundational ideas: values, variables, expressions, and functions. These are not advanced topics. They are the basic materials that JavaScript uses to do anything at all. Understanding them well is not optional. Everything in the chapters that follow — events, the DOM, forms, loops, dynamic content — depends directly on what you learn here.
This chapter teaches these ideas slowly and clearly. You will read many short examples, trace the flow of values through statements, write small programs and predict what they produce, and learn the most common beginner mistakes so you can recognize and fix them in your own code.
What do a price on a shopping page, the number of items in a cart, the text a visitor typed into a search box, and a message that says "Welcome back" all have in common? Each one is a value that a JavaScript program stores, calculates, or displays. By the end of this chapter, you will know how to create those values, store them in named variables, combine them in expressions, and package logic into reusable functions that accept input and return output.
By the end of this chapter, you should be able to:
let and const, and explain when to use each.typeof to check a value's type.${}.function keyword, a parameter list, and a body.let and constDeclaring and reassigning variables; choosing let versus const; avoiding vartypeof operator${} interpolation; multi-line strings; building HTML fragments from datafunction keyword; the function body; defining a function versus running itreturn statement; undefined; early returnEvery JavaScript program works with values. A value is a piece of data. It can be a word, a number, a yes/no answer, or nothing at all. When JavaScript runs a statement, it is almost always doing something with a value: storing it, checking it, changing it, or sending it somewhere.
Here are some examples of values written directly in JavaScript:
"Hello, world" 42 3.14 true false
The first value is a piece of text. The second and third are numbers. The fourth and fifth are the special values true and false, which represent yes/no decisions.
A value written directly in code — like 42 or "Hello" — is called a literal. It is a fixed value that you have typed out completely.
console.log(42);
console.log("Hello, world");
console.log(true);
Each of these statements sends a value to the browser console. There is no calculation happening yet — these are just values being used directly.
Without values, a program could not store any information, make any decisions, or produce any results. Every piece of meaningful output — a message on screen, a number in a calculation, a yes/no check — begins with a value. In web development, values represent things like:
You will use values constantly. Understanding how JavaScript handles them is the foundation of everything else.
let and constA variable is a named container that holds a value. Instead of repeating the same value over and over in your code, you store it in a variable once and refer to it by name whenever you need it.
letTo create a variable in modern JavaScript, you use the keyword let followed by a name and an equals sign, then the value you want to store:
let greeting = "Hello, visitor"; let pageCount = 5; let siteIsOpen = true;
After these statements run, the variable greeting holds the string "Hello, visitor", pageCount holds the number 5, and siteIsOpen holds the value true. You can then use these variables anywhere you would use their values:
console.log(greeting); console.log(pageCount); console.log(siteIsOpen);
letVariables declared with let can be changed after they are created. This is called reassigning the variable:
let score = 0; console.log(score); score = 10; console.log(score); score = 25; console.log(score);
Notice that when you reassign a variable, you do not use the let keyword again. You only use let the first time, when you are declaring the variable. After that, you just write the name and the new value.
constIf you have a value that should never change, use const instead of let:
const siteName = "Learning Hub"; const maxLoginAttempts = 3;
A variable declared with const cannot be reassigned. If you try, JavaScript will throw an error:
const siteName = "Learning Hub";
siteName = "New Name"; // Error: Assignment to constant variable.
Use const by default. Use let when you know the value needs to change. If you are storing a site title, a configuration value, or anything that will stay the same throughout the script, use const. If you are counting, tracking a changing state, or reading a value that will update, use let.
Good habit in practice:
const siteName = "Learning Hub"; // Will not change const maxItems = 10; // Will not change let currentCount = 0; // Will change as items are added let menuIsOpen = false; // Will change when user clicks
varYou may see older JavaScript code using the keyword var to declare variables. This keyword behaves differently from let and const in ways that can cause confusing bugs. Modern JavaScript uses let and const. You do not need var for any of the work in this textbook.
JavaScript organizes values into categories called data types. The three most important data types for beginners are strings, numbers, and Booleans.
A string is a sequence of characters — letters, digits, spaces, punctuation — treated as text. Strings are written inside quotation marks. You can use double quotes or single quotes. Both work:
let firstName = "Alex"; let lastName = 'Rivera';
You can also use backtick characters, which create a special kind of string called a template literal (covered in Section 20.5). Strings can contain spaces, numbers, and punctuation, as long as they are inside the quotes:
let message = "Your score is 42 out of 100."; let address = "123 Main St., Unit 4B";
If you want to include a quotation mark inside a string that uses the same type of quote, you need to escape it with a backslash:
let note = "She said, \"Good morning!\"";
Or you can simply switch quote types:
let note = 'She said, "Good morning!"';
A number in JavaScript can be a whole number (integer) or a decimal:
let itemCount = 7; let price = 12.99; let temperature = -4; let percentage = 0.75;
Unlike strings, numbers are written without quotation marks. Notice the difference:
let a = 42; // This is the number 42 let b = "42"; // This is the string "42" — the text characters 4 and 2
These look similar but behave very differently. You can do arithmetic with the number 42. You cannot do arithmetic with the string "42" in the same way. This distinction matters for form validation and calculations in later chapters.
A Boolean is a value that is either true or false. There are no other options.
let isLoggedIn = false; let hasCompletedForm = true; let menuIsVisible = false;
Booleans are not strings. They are written without quotation marks. true and false are special keywords in JavaScript. Booleans become essential when your JavaScript needs to make decisions. You will use them extensively starting in Chapter 23.
typeofIf you are ever unsure what type a value is, you can use the typeof operator:
console.log(typeof "Hello"); // string console.log(typeof 42); // number console.log(typeof true); // boolean
The typeof operator is especially useful for debugging — when a value behaves unexpectedly, checking its type is often the fastest way to discover what went wrong.
An expression is any piece of code that produces a value. Expressions can be simple — just a single value — or they can involve calculations, comparisons, and combinations.
JavaScript supports the standard arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 3 * 6 | 18 |
/ | Division | 20 / 4 | 5 |
% | Remainder | 10 % 3 | 1 |
The % operator (called the modulo operator) gives you the remainder after division. For example, 10 % 3 is 1 because 10 divided by 3 is 3 remainder 1. You will use this in later chapters for tasks like checking whether a number is odd or even.
let a = 12; let b = 5; console.log(a + b); // 17 console.log(a - b); // 7 console.log(a * b); // 60 console.log(a / b); // 2.4 console.log(a % b); // 2
The + operator also works with strings. When used with two strings, it joins them together. This is called concatenation:
let first = "Web";
let second = "Development";
let combined = first + " " + second;
console.log(combined); // Web Development
Note the space in " ". Without it, the result would be "WebDevelopment" with no space between the words. Mixing strings and numbers with + can produce surprising results:
console.log("The total is: " + 42); // The total is: 42
console.log(10 + "5"); // 105
In the second example, JavaScript converts the number 10 to a string and concatenates, giving "105" instead of 15. This is a common source of confusion for beginners. When you need to add numbers from form inputs, you will need to explicitly convert them. That topic appears in Chapter 24.
You have already seen the basic assignment operator =. There are shorthand versions:
let count = 0; count = count + 1; // Add 1 count += 1; // Same thing, shorter count = count * 2; // Multiply by 2 count *= 2; // Same thing, shorter
The shorthand operators +=, -=, *=, and /= are very common. You will see them often.
Adding or subtracting 1 from a number is so common that JavaScript has special syntax:
let count = 5; count++; // count is now 6 count--; // count is now 5 again console.log(count); // 5
count++ adds 1. count-- subtracts 1. These are called the increment and decrement operators.
Like mathematics, JavaScript evaluates expressions in a specific order. Multiplication and division happen before addition and subtraction. Use parentheses to control the order explicitly:
console.log(2 + 3 * 4); // 14, not 20 — multiplication first console.log((2 + 3) * 4); // 20 — parentheses first
When in doubt, use parentheses. They make the intention clear to both JavaScript and to readers of your code.
String concatenation with + works, but it becomes awkward when you want to build longer strings with several pieces of data. Template literals are a cleaner way to write strings that include variable values.
Template literals use backticks instead of quotation marks. Inside a template literal, you use ${expression} to insert a value:
let userName = "Alex";
let score = 95;
let message = `Hello, ${userName}. Your score is ${score}.`;
console.log(message);
Compare this to the concatenation version:
let message = "Hello, " + userName + ". Your score is " + score + ".";
Both produce the same result, but the template literal version is easier to read and harder to get wrong.
The ${} placeholder can hold any expression, not just a variable name:
let width = 8;
let height = 5;
console.log(`The area is ${width * height} square units.`);
Template literals also support multi-line strings without special characters:
let poem = `Roses are red, Violets are blue, JavaScript is useful, And so are you.`; console.log(poem);
This produces four lines of output as written. With regular quotes, you would need \n to create line breaks.
Template literals become especially valuable in Chapter 22 and beyond, when you build HTML strings in JavaScript and insert them into the page. For example:
let title = "Beginner Guide";
let author = "J. Reyes";
let cardHTML = `<div class="card">
<h2>${title}</h2>
<p>By ${author}</p>
</div>`;
This kind of pattern — building HTML from data using template literals — is central to dynamic web development. You are learning the foundation of it now.
So far, every example has run its statements once, from top to bottom. Functions let you give a name to a block of statements and run them whenever you choose.
A function is a named, reusable block of code. You define it once, then call it as many times as needed.
function greet() {
console.log("Hello, visitor!");
console.log("Welcome to the site.");
}
This defines a function named greet. It contains two statements. Notice:
functiongreet)() after the name{} enclosing the function bodyDefining a function does not run it. The statements inside are stored but not executed yet. A function only runs when it is called — you will learn how in Section 20.7.
Everything between the curly braces is the function body. This is the code that runs when the function is called.
function displayPageTitle() {
console.log("Page: About Us");
console.log("Section: Team");
console.log("Status: Live");
}
To run a function, you call it by writing its name followed by parentheses:
greet();
This tells JavaScript: find the function named greet and run its body right now.
function greet() {
console.log("Hello, visitor!");
console.log("Welcome to the site.");
}
greet(); // Calls the function — runs both console.log statements
greet(); // Calls it again — runs them a second time
greet(); // Calls it a third time
The function body ran three times because the function was called three times. You define the code once and reuse it as many times as needed.
In most cases, it is good practice to define your functions before you call them. JavaScript actually allows a specific behavior called hoisting, where function declarations (written with the function keyword) can be called before they appear in the file. This can be confusing at first, so for now, define your functions before calling them.
// Define first function showWelcome() { console.log("Welcome to the Learning Hub."); } // Then call showWelcome();
The greet() function from the previous section always prints the same message. That is fine for some purposes, but often you want a function to work with different data each time it runs.
A parameter is a named placeholder inside the function definition. When you call the function, you pass in a value, and that value is used inside the function body.
function greet(name) {
console.log(`Hello, ${name}! Welcome to the site.`);
}
Here, name is the parameter. It is like a variable, but it only exists inside the function. Now when you call the function, you provide the value you want to use:
greet("Alex");
greet("Jordan");
greet("Sam");
The same function works differently depending on what value you pass in.
A parameter is the name in the function definition: name in function greet(name). An argument is the actual value you pass when calling: "Alex" in greet("Alex"). The terms are often used interchangeably in conversation, but the distinction is useful to know.
Functions can accept more than one parameter. Separate them with commas:
function describePage(title, author, year) {
console.log(`Title: ${title}`);
console.log(`Author: ${author}`);
console.log(`Year: ${year}`);
}
describePage("HTML Fundamentals", "L. Torres", 2024);
describePage("CSS Layout Guide", "M. Park", 2023);
Arguments are matched to parameters in order: the first argument goes to the first parameter, the second to the second, and so on.
So far, functions have produced output by calling console.log(). But often, you want a function to calculate something and give the result back to the rest of your code. You do this with the return statement.
function add(a, b) {
return a + b;
}
When JavaScript reaches return, it stops the function and sends the value back to wherever the function was called.
let result = add(5, 3);
console.log(result); // 8
The function ran, calculated 5 + 3, returned 8, and that value was stored in result. You can use the returned value directly in expressions:
let total = add(10, 20) + add(5, 5);
console.log(total); // 40
function formatTitle(title, section) {
return `${section}: ${title}`;
}
let pageTitle = formatTitle("Introduction to HTML", "Chapter 5");
console.log(pageTitle); // Chapter 5: Introduction to HTML
A function that does not have a return statement (or whose return has no value) returns undefined. This is a special JavaScript value meaning "nothing." You will see it in the console if you try to use the result of a void function as if it returned something.
function sayHello() {
console.log("Hello!");
}
let x = sayHello();
console.log(x); // undefined
This is not an error. It simply means the function did not provide a value to store.
A function can return early based on a condition. Return also stops execution inside the function:
function checkLength(text) {
if (text.length === 0) {
return "Empty";
}
return "Has content";
}
console.log(checkLength("")); // Empty
console.log(checkLength("Hello")); // Has content
You will use early return frequently in Chapter 24 when writing form validation logic.
Code is read far more often than it is written. Clear, descriptive names make code easier to understand, easier to debug, and easier to maintain.
Variable names should describe what the variable holds. Avoid single-letter names except in very short loops and mathematical operations.
let x = "Alex"; let n = 42; let f = true;
let userName = "Alex"; let questionCount = 42; let formIsValid = true;
Function names should describe what the function does. Use a verb or verb phrase. Functions perform actions, so their names should read like actions.
function data(title, year) { ... }
function thing() { ... }
function formatCitation(title, year) { ... }
function displayWelcomeMessage() { ... }
JavaScript variables and function names traditionally use camelCase: the first word is lowercase, and each following word begins with a capital letter.
let pageTitle = "Home";
let itemCount = 0;
let menuIsVisible = false;
function formatPageTitle(title) { ... }
function countVisibleItems() { ... }
function toggleNavMenu() { ... }
Constants that represent fixed configuration values are sometimes written in ALL_CAPS_WITH_UNDERSCORES:
const MAX_RESULTS = 20; const DEFAULT_COLOR = "#333333";
This is a convention, not a rule enforced by JavaScript. Either style is technically valid. For beginners, using camelCase for everything is simpler.
Comments explain why code exists or what a non-obvious section does. They are ignored by JavaScript — they are for human readers.
// Single-line comment /* Multi-line comment. Use for longer explanations. */ function calculateDiscount(price, rate) { // rate is a decimal, e.g., 0.1 for 10% return price * rate; }
Good comments explain intent, not what the code obviously does:
// Not useful: let x = x + 1; // adds 1 to x // Useful: let retryCount = retryCount + 1; // Track how many times the user has tried
JavaScript does not require indentation, but it is expected. Function bodies are indented by two or four spaces. Nested structures are indented further. Consistent indentation makes code readable and helps you spot structural errors like missing braces.
function gradeScore(score) {
if (score >= 90) {
return "Excellent";
} else if (score >= 70) {
return "Passing";
} else {
return "Needs improvement";
}
}
One of the most important skills in programming is tracing: reading a program carefully and predicting what it will produce, step by step. Tracing is not just a classroom exercise. It is how experienced developers read unfamiliar code, diagnose bugs, and verify logic. This section gives you several examples to trace, with explanations.
let count = 0; count = count + 5; count = count * 2; count = count - 3; console.log(count);
| Line | Statement | Value of count |
|---|---|---|
| 1 | let count = 0 | 0 |
| 2 | count = 0 + 5 | 5 |
| 3 | count = 5 * 2 | 10 |
| 4 | count = 10 - 3 | 7 |
| 5 | console.log(7) | output: 7 |
function double(n) {
return n * 2;
}
let a = double(4);
let b = double(a);
console.log(b);
double(4) is called. n is 4. 4 * 2 is 8. Return 8.a is assigned 8.double(a) is called. a is 8, so n is 8. 8 * 2 is 16. Return 16.b is assigned 16.console.log(16) runs.function formatLabel(item, count) {
return `${item}: ${count} available`;
}
let label = formatLabel("Pencils", 12);
console.log(label);
formatLabel("Pencils", 12) is called. item is "Pencils", count is 12."Pencils: 12 available"."Pencils: 12 available".label stores "Pencils: 12 available".console.log("Pencils: 12 available") runs.function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
let x = add(3, 4);
let y = multiply(x, 2);
let z = add(y, 1);
console.log(x);
console.log(y);
console.log(z);
add(3, 4) → returns 7. x = 7.multiply(7, 2) → returns 14. y = 14.add(14, 1) → returns 15. z = 15.function buildGreeting(hour, name) {
let period = "morning";
if (hour >= 12) {
period = "afternoon";
}
return `Good ${period}, ${name}.`;
}
let message = buildGreeting(14, "Jordan");
console.log(message);
buildGreeting(14, "Jordan") is called. hour is 14, name is "Jordan".period starts as "morning".period becomes "afternoon"."Good afternoon, Jordan.".message and logged.Trace Example 5 uses an if statement, which you will study fully in Chapter 23. For now, notice how the function produces different results depending on the value of hour.
Let us apply everything in this chapter to a realistic problem. You want a JavaScript function that takes a page title, an author name, and a word count, and returns a formatted summary string suitable for display or logging.
What does it need?
What should the output look like?
function buildPageSummary(title, author, wordCount) {
return `"${title}" by ${author} — ${wordCount} words`;
}
let summary1 = buildPageSummary("Introduction to CSS", "L. Torres", 1240);
let summary2 = buildPageSummary("Flexbox Layout", "M. Park", 980);
let summary3 = buildPageSummary("Responsive Design", "A. Reyes", 1550);
console.log(summary1);
console.log(summary2);
console.log(summary3);
What if you want to display a short message if the word count is over 1000?
function buildPageSummary(title, author, wordCount) {
let lengthNote = "";
if (wordCount > 1000) {
lengthNote = " (long read)";
}
return `"${title}" by ${author} — ${wordCount} words${lengthNote}`;
}
console.log(buildPageSummary("Introduction to CSS", "L. Torres", 1240));
console.log(buildPageSummary("Quick Start Guide", "J. Kim", 350));
This function now uses a variable (lengthNote), a conditional (if), and a template literal together. You have all the tools to read and write this code.
const for values that should not change and let for values that will change. Avoid var in modern JavaScript.typeof operator reveals a value's type — useful for debugging.${} and support multi-line strings. They are the standard way to build readable strings from data.function keyword, a name, parentheses, and a body. Defining a function does not run it.return statement sends a value back to the caller; without it, a function returns undefined.=.true or false.pageTitle.+ operator.function keyword, a name, parameters, and a body.count++ or count += 1.42, "Hello", or true.% operator. Returns the remainder after division.${}.These are the errors beginners encounter most often with variables, values, expressions, and functions.
= instead of === for comparison// Wrong intention: if (score = 100) { ... } // This assigns 100 to score, always true // Correct: if (score === 100) { ... } // This compares score to 100
The single = assigns. The triple === compares. You will use === for comparisons in Chapter 23. Be aware of this distinction now.
let name = Alex; // Error: JavaScript thinks Alex is a variable name let name = "Alex"; // Correct
constconst siteTitle = "Learning Hub";
siteTitle = "New Title"; // Error: Assignment to constant variable
If the value needs to change, use let.
greet(); // Works with function declarations due to hoisting const greet = function() { // Function expression — NOT hoisted console.log("Hello"); };
For beginners, always define functions before calling them to avoid confusion.
function greet(name { // Missing closing parenthesis — syntax error
console.log("Hello");
}
Every opening ( needs a matching ). Every opening { needs a matching }. The browser cannot run a file with unmatched brackets.
let a = "5";
let b = "3";
console.log(a + b); // "53" — string concatenation, not addition
If you want to add numbers, make sure they are numbers, not strings. You will learn parseInt() and parseFloat() in Chapter 24.
return in a functionfunction add(a, b) {
a + b; // Calculates but does not return the result
}
let result = add(5, 3);
console.log(result); // undefined
If a function should give a value back, it must use return.
Evaluate each expression. Write what value it produces.
5 + 310 - 4 * 2(10 - 4) * 2"Hello" + " " + "World"12 % 5typeof "banana"typeof 99typeof trueFor each of the following, identify whether the result is a string, number, or Boolean:
"42"42false"false"3.14"3.14"Trace each program and write its complete output.
function square(n) {
return n * n;
}
let a = square(3);
let b = square(5);
let c = square(a);
console.log(a);
console.log(b);
console.log(c);
function makeFull(first, last) {
return first + " " + last;
}
let name1 = makeFull("Alex", "Rivera");
let name2 = makeFull("Jordan", "Kim");
console.log(name1);
console.log(`Hello, ${name2}!`);
let x = 10; x += 5; x *= 2; x -= 7; console.log(x);
function describe(animal, sound) {
return `The ${animal} says ${sound}.`;
}
console.log(describe("dog", "woof"));
console.log(describe("cat", "meow"));
console.log(describe("duck", "quack"));
For each block of code, write what you think will appear in the console. Then open your browser console and test it.
let a = 4; let b = a + 3; let c = b * 2; console.log(c);
function greet(name) {
return `Hello, ${name}!`;
}
let msg = greet("Sam");
console.log(msg);
console.log(msg.length);
function isLong(text) {
return text.length > 10;
}
console.log(isLong("hi"));
console.log(isLong("JavaScript is interesting"));
let count = 0; count++; count++; count++; count--; console.log(count);
Each block of code contains one or more errors. Identify the error and write the corrected version.
let userName = Alex; console.log(userName);
const score = 80; score = 95; console.log(score);
function add(a, b) {
a + b;
}
let result = add(3, 4);
console.log(result);
function greet(name {
console.log("Hello, " + name);
}
greet("Alex");
let price = "20"; let tax = "5"; let total = price + tax; console.log(total);
Explain: why does this not produce 25? How would you fix it?
Write each function in your text editor, link your script file, and test in the console.
greetUser that takes a name parameter and returns the string "Welcome, [name]!".calculateArea that takes width and height as parameters and returns their product.formatPrice that takes a price (number) and returns it as a formatted string like "Price: $12.99". Use a template literal.fullName that takes firstName and lastName and returns the full name as a single string with a space between them.isShort that takes a string and returns true if its length is 5 or fewer characters, and false otherwise.itemCount starting at 0. Write a function called addItem that takes a number and returns the sum of itemCount and that number. Call addItem(5) three times and log each result."[Title] — [Author] ([Year])". Use three variables and a function.You have been building the Student Learning Site throughout this course. Now you will add a small JavaScript file that uses variables, expressions, and functions.
In your project folder, open js/main.js.
Add variables that describe the current page:
const siteName = "Student Learning Site"; const currentPage = "Resources"; const resourceCount = 12;
Write a function that takes the time of day (as a number from 0 to 23) and returns a greeting:
function timeGreeting(hour) {
if (hour < 12) {
return "Good morning";
} else if (hour < 18) {
return "Good afternoon";
} else {
return "Good evening";
}
}
Write a function that takes a page name and an item count and returns a summary string:
function pageSummary(page, count) {
return `${page} — ${count} items available`;
}
let currentHour = 14;
let greeting = timeGreeting(currentHour);
console.log(`${greeting}. Welcome to ${siteName}.`);
console.log(pageSummary(currentPage, resourceCount));
Open your HTML file. Open the browser console (F12 or right-click → Inspect → Console). You should see:
Modify the timeGreeting function so it also includes the user's name:
function timeGreeting(hour, name) {
let period = "morning";
if (hour >= 12 && hour < 18) {
period = "afternoon";
} else if (hour >= 18) {
period = "evening";
}
return `Good ${period}, ${name}`;
}
console.log(timeGreeting(14, "Alex"));
This chapter focuses on pure JavaScript logic without interaction with the page yet. Even so, keep in mind that functions and variables used in later chapters will support accessible behavior — announcing messages to screen readers, managing focus, and validating form fields before submission. Clean, well-named code makes it easier to identify where accessibility features are implemented. Start building that habit now.
const instead of let? Give an example of each."42" and the number 42? Why does it matter?+ operator."Hello, " + name + ". You have " + count + " messages."return statement do? What happens if a function has no return statement?function triple(n) {
return n * 3;
}
let a = 4;
let b = triple(a);
let c = triple(b) - 5;
console.log(a);
console.log(b);
console.log(c);
const maxItems = 10; maxItems = 20;
console.log("3" + 4);
let x = "A. Rivera"; let y = 42; let z = true;
typeof do? Write three examples using different data types.let and const and explain when to use each.typeof to check a value's type.${}.You now have the tools to store values, calculate with them, and organize code into functions. The next step is to make your page respond to people. Chapter 21 introduces events — the mechanism JavaScript uses to detect user actions. You will learn how to attach event listeners to buttons, links, and other elements, and how to run a function whenever a user clicks, types, or interacts. You will also write your first functions that respond to events and update visible parts of the page. Events are where JavaScript moves from scripts that run once on load to scripts that respond to real human behavior. Everything you learned in this chapter — variables, template literals, functions, return values — will become the logic inside your event-driven code.