MGU Computer Science Series — Web Development: HTML, CSS, and JavaScript
Part IV: JavaScript — Interaction and Logic
Values · Variables · Expressions · Functions
Chapter 20 of 30
20
MGU Computer Science Series  ·  Web Development: HTML, CSS, and JavaScript  ·  Library Textbook Edition

Chapter 20:
Variables, Values, Expressions,
and Functions in JavaScript

The building blocks of every JavaScript program — values, variables, expressions, template literals, and functions that accept input and return output

■ Part IV of VII ■

■ 10 Sections  •  Chapter 20 of 30 ■

Builds directly on Chapter 19 — no prior programming background required

Chapter Introduction and Learning Objectives

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.

Opening Question

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.

10Sections
11Objectives
27Key Terms
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Explain what a value is and identify the basic kinds of values JavaScript works with.
  2. 2Declare variables using let and const, and explain when to use each.
  3. 3Distinguish strings, numbers, and Booleans, and use typeof to check a value's type.
  4. 4Write expressions using arithmetic, string concatenation, and assignment operators.
  5. 5Explain operator precedence and use parentheses to control the order of evaluation.
  6. 6Build strings with template literals and embed expressions inside them using ${}.
  7. 7Define a function using the function keyword, a parameter list, and a body.
  8. 8Call a function and explain the difference between defining a function and running it.
  9. 9Explain parameters, arguments, and return values, and write functions that return a value.
  10. 10Apply naming conventions such as camelCase and write readable, well-commented code.
  11. 11Trace a small JavaScript program by hand, step by step, and correctly predict its output.

Sections at a Glance

Values in JavaScript

Every 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.

Why Values Matter

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:

  • The text a user typed into a form field
  • The current count of items in a list
  • Whether a menu is currently open or closed
  • The title of a page or section
  • A price, a score, a measurement

You will use values constantly. Understanding how JavaScript handles them is the foundation of everything else.

Variables with let and const

A 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.

Declaring a Variable with let

To 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);
OutputHello, visitor 5 true

Changing a Variable with let

Variables 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);
Output0 10 25

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.

Declaring a Constant with const

If 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.
A Simple Rule

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
Avoid var

You 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.

Strings, Numbers, and Booleans

JavaScript organizes values into categories called data types. The three most important data types for beginners are strings, numbers, and Booleans.

Strings

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!"';

Numbers

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.

Booleans

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.

Checking Types with typeof

If 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
Study Note

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.

Expressions and Operators

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.

Arithmetic Operators

JavaScript supports the standard arithmetic operators:

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication3 * 618
/Division20 / 45
%Remainder10 % 31

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

String Concatenation

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
Watch Out

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.

Assignment Operators

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.

Increment and Decrement

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.

Operator Precedence

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
Study Note

When in doubt, use parentheses. They make the intention clear to both JavaScript and to readers of your code.

Template Literals

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);
OutputHello, Alex. Your score is 95.

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.

Expressions Inside Template Literals

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.`);
OutputThe area is 40 square units.

Multi-Line Strings

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 and the DOM

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>`;
Looking Ahead

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.

Defining Functions

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.

The Basic Function Definition

function greet() {
  console.log("Hello, visitor!");
  console.log("Welcome to the site.");
}

This defines a function named greet. It contains two statements. Notice:

  • The keyword function
  • The function name (greet)
  • Parentheses () after the name
  • Curly braces {} enclosing the function body
  • The statements inside the body, indented for readability
A Key Distinction

Defining 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.

The Function Body

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");
}

Calling Functions

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
OutputHello, visitor! Welcome to the site. Hello, visitor! Welcome to the site. Hello, visitor! Welcome to the site.

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.

Order of Definition and Calls

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();

Parameters and Return Values

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.

Parameters

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");
OutputHello, Alex! Welcome to the site. Hello, Jordan! Welcome to the site. Hello, Sam! Welcome to the site.

The same function works differently depending on what value you pass in.

Parameters Versus Arguments

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.

Multiple Parameters

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);
OutputTitle: HTML Fundamentals Author: L. Torres Year: 2024 Title: CSS Layout Guide Author: M. Park Year: 2023

Arguments are matched to parameters in order: the first argument goes to the first parameter, the second to the second, and so on.

Return Values

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
A function that returns a formatted string
function formatTitle(title, section) {
  return `${section}: ${title}`;
}

let pageTitle = formatTitle("Introduction to HTML", "Chapter 5");
console.log(pageTitle);   // Chapter 5: Introduction to HTML

Functions Without Return

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.

Early Return

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
Looking Ahead

You will use early return frequently in Chapter 24 when writing form validation logic.

Naming and Readability

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.

Naming Variables

Variable names should describe what the variable holds. Avoid single-letter names except in very short loops and mathematical operations.

Less readable
let x = "Alex";
let n = 42;
let f = true;
More readable
let userName = "Alex";
let questionCount = 42;
let formIsValid = true;

Naming Functions

Function names should describe what the function does. Use a verb or verb phrase. Functions perform actions, so their names should read like actions.

Less readable
function data(title, year) { ... }
function thing() { ... }
More readable
function formatCitation(title, year) { ... }
function displayWelcomeMessage() { ... }

camelCase

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

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

Indentation

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";
  }
}

Tracing Small JavaScript Programs

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.

Trace Example 1
Variable reassignment
let count = 0;
count = count + 5;
count = count * 2;
count = count - 3;
console.log(count);
LineStatementValue of count
1let count = 00
2count = 0 + 55
3count = 5 * 210
4count = 10 - 37
5console.log(7)output: 7
Output7
Trace Example 2
Function with return
function double(n) {
  return n * 2;
}

let a = double(4);
let b = double(a);
console.log(b);
  1. double(4) is called. n is 4. 4 * 2 is 8. Return 8.
  2. a is assigned 8.
  3. double(a) is called. a is 8, so n is 8. 8 * 2 is 16. Return 16.
  4. b is assigned 16.
  5. console.log(16) runs.
Output16
Trace Example 3
Template literal
function formatLabel(item, count) {
  return `${item}: ${count} available`;
}

let label = formatLabel("Pencils", 12);
console.log(label);
  1. formatLabel("Pencils", 12) is called. item is "Pencils", count is 12.
  2. Template literal produces "Pencils: 12 available".
  3. Function returns "Pencils: 12 available".
  4. label stores "Pencils: 12 available".
  5. console.log("Pencils: 12 available") runs.
OutputPencils: 12 available
Trace Example 4
Multiple function calls
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);
  1. add(3, 4) → returns 7. x = 7.
  2. multiply(7, 2) → returns 14. y = 14.
  3. add(14, 1) → returns 15. z = 15.
Output7 14 15
Trace Example 5
A realistic web function
function buildGreeting(hour, name) {
  let period = "morning";
  if (hour >= 12) {
    period = "afternoon";
  }
  return `Good ${period}, ${name}.`;
}

let message = buildGreeting(14, "Jordan");
console.log(message);
  1. buildGreeting(14, "Jordan") is called. hour is 14, name is "Jordan".
  2. period starts as "morning".
  3. The comparison is true, since 14 is at least 12, so period becomes "afternoon".
  4. Template literal produces "Good afternoon, Jordan.".
  5. Function returns the string, which is stored in message and logged.
OutputGood afternoon, Jordan.
Study Note

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.

Building a Page Summary Function

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.

Planning the Function

What does it need?

  • Three inputs: title (string), author (string), wordCount (number)
  • One output: a formatted summary string

What should the output look like?

Target Output"Introduction to CSS" by L. Torres — 1,240 words

Writing the Function

function buildPageSummary(title, author, wordCount) {
  return `"${title}" by ${author} — ${wordCount} words`;
}

Testing the Function

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);
Output"Introduction to CSS" by L. Torres — 1240 words "Flexbox Layout" by M. Park — 980 words "Responsive Design" by A. Reyes — 1550 words

Extending the Function

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));
Output"Introduction to CSS" by L. Torres — 1240 words (long read) "Quick Start Guide" by J. Kim — 350 words
What You Just Used

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.

Chapter Summary

Key Terms

argument
A value passed to a function when it is called. Matched to the function's parameters in order.
assignment
Storing a value in a variable using =.
Boolean
A data type with exactly two values: true or false.
camelCase
A naming convention where the first word is lowercase and subsequent words begin with a capital letter. Example: pageTitle.
concatenation
Joining two strings together using the + operator.
const
A keyword for declaring a variable whose value cannot be reassigned.
data type
A category that describes what kind of value a variable holds. Common types: string, number, Boolean.
expression
Any code that evaluates to a value.
function
A named, reusable block of code that can accept inputs (parameters) and return an output.
function body
The statements inside a function's curly braces.
function call
Running a function by writing its name followed by parentheses, with any arguments inside.
function definition
Declaring a function with the function keyword, a name, parameters, and a body.
increment
Adding 1 to a number. Written as count++ or count += 1.
let
A keyword for declaring a variable whose value can be changed later.
literal
A value written directly in code, such as 42, "Hello", or true.
modulo
The % operator. Returns the remainder after division.
number
A JavaScript data type representing numeric values, including integers and decimals.
operator
A symbol that performs an operation on one or more values.
parameter
A named placeholder in a function definition that holds an argument's value when the function runs.
reassignment
Changing the value stored in a variable after it has been declared.
return
A statement that ends a function and sends a value back to the caller.
string
A JavaScript data type representing text, enclosed in quotes.
template literal
A string written with backticks that can embed expressions using ${}.
tracing
Reading code step by step and predicting what it will produce.
typeof
An operator that returns the data type of a value as a string.
undefined
A special JavaScript value meaning "no value was returned" or "this variable has not been assigned."
variable
A named container that stores a value.

Common Mistakes

These are the errors beginners encounter most often with variables, values, expressions, and functions.

Mistake 1
Using = 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.

Mistake 2
Forgetting quotes around strings
let name = Alex;   // Error: JavaScript thinks Alex is a variable name
let name = "Alex"; // Correct
Mistake 3
Trying to reassign a const
const siteTitle = "Learning Hub";
siteTitle = "New Title";   // Error: Assignment to constant variable

If the value needs to change, use let.

Mistake 4
Calling a function before defining it (when using expressions)
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.

Mistake 5
Mismatched parentheses or braces
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.

Mistake 6
Concatenating when you meant to add
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.

Mistake 7
Missing return in a function
function 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.

PracticeJavaScript Expression Practice

Evaluate each expression. Write what value it produces.

  1. 5 + 3
  2. 10 - 4 * 2
  3. (10 - 4) * 2
  4. "Hello" + " " + "World"
  5. 12 % 5
  6. typeof "banana"
  7. typeof 99
  8. typeof true

For each of the following, identify whether the result is a string, number, or Boolean:

  1. "42"
  2. 42
  3. false
  4. "false"
  5. 3.14
  6. "3.14"
PracticeFunction Tracing

Trace each program and write its complete output.

Program A
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);
Program B
function makeFull(first, last) {
  return first + " " + last;
}

let name1 = makeFull("Alex", "Rivera");
let name2 = makeFull("Jordan", "Kim");

console.log(name1);
console.log(`Hello, ${name2}!`);
Program C
let x = 10;
x += 5;
x *= 2;
x -= 7;

console.log(x);
Program D
function describe(animal, sound) {
  return `The ${animal} says ${sound}.`;
}

console.log(describe("dog", "woof"));
console.log(describe("cat", "meow"));
console.log(describe("duck", "quack"));
PracticePredict the Output

For each block of code, write what you think will appear in the console. Then open your browser console and test it.

Block 1
let a = 4;
let b = a + 3;
let c = b * 2;
console.log(c);
Block 2
function greet(name) {
  return `Hello, ${name}!`;
}

let msg = greet("Sam");
console.log(msg);
console.log(msg.length);
Block 3
function isLong(text) {
  return text.length > 10;
}

console.log(isLong("hi"));
console.log(isLong("JavaScript is interesting"));
Block 4
let count = 0;
count++;
count++;
count++;
count--;
console.log(count);
PracticeDebugging Practice

Each block of code contains one or more errors. Identify the error and write the corrected version.

Debug 1
let userName = Alex;
console.log(userName);
Debug 2
const score = 80;
score = 95;
console.log(score);
Debug 3
function add(a, b) {
  a + b;
}

let result = add(3, 4);
console.log(result);
Debug 4
function greet(name {
  console.log("Hello, " + name);
}
greet("Alex");
Debug 5
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?

PracticeShort Coding Tasks

Write each function in your text editor, link your script file, and test in the console.

  1. Write a function called greetUser that takes a name parameter and returns the string "Welcome, [name]!".
  2. Write a function called calculateArea that takes width and height as parameters and returns their product.
  3. Write a function called formatPrice that takes a price (number) and returns it as a formatted string like "Price: $12.99". Use a template literal.
  4. Write a function called fullName that takes firstName and lastName and returns the full name as a single string with a space between them.
  5. Write a function called isShort that takes a string and returns true if its length is 5 or fewer characters, and false otherwise.
  6. Write a variable 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.
  7. Use a template literal to build a string that displays this format: "[Title] — [Author] ([Year])". Use three variables and a function.
Mini-ProjectScript for the Student Learning Site

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.

Setup

In your project folder, open js/main.js.

Step 1: Page Information Variables

Add variables that describe the current page:

const siteName = "Student Learning Site";
const currentPage = "Resources";
const resourceCount = 12;

Step 2: A Greeting Function

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";
  }
}

Step 3: A Page Summary Function

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`;
}

Step 4: Log Results to the Console

let currentHour = 14;
let greeting = timeGreeting(currentHour);

console.log(`${greeting}. Welcome to ${siteName}.`);
console.log(pageSummary(currentPage, resourceCount));

Step 5: Open the Page in Your Browser

Open your HTML file. Open the browser console (F12 or right-click → Inspect → Console). You should see:

Console OutputGood afternoon. Welcome to Student Learning Site. Resources — 12 items available

Extension

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"));

Accessibility Note

Building Good Habits Early

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.

ReviewReview Questions
  1. What is the difference between a value and a variable?
  2. When should you use const instead of let? Give an example of each.
  3. What are the three main data types introduced in this chapter?
  4. What is the difference between the string "42" and the number 42? Why does it matter?
  5. What is concatenation? Write an example using the + operator.
  6. What is a template literal? Rewrite this expression using a template literal: "Hello, " + name + ". You have " + count + " messages."
  7. What is the difference between defining a function and calling a function?
  8. What is a parameter? What is an argument? How are they related?
  9. What does the return statement do? What happens if a function has no return statement?
  10. Trace this program and write its output:
    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);
  11. What is wrong with this code?
    const maxItems = 10;
    maxItems = 20;
  12. What is the output of this expression, and why?
    console.log("3" + 4);
  13. Why is naming variables clearly important? Rewrite these with better names:
    let x = "A. Rivera";
    let y = 42;
    let z = true;
  14. What does typeof do? Write three examples using different data types.
  15. What does it mean to trace a program? Why is tracing a useful skill?
Chapter 20 Checklist
Use this to confirm your understanding before moving to Chapter 21
Concepts
  • I can explain what a value is and identify literals in code.
  • I can declare variables with let and const and explain when to use each.
  • I can distinguish strings, numbers, and Booleans, and use typeof to check a value's type.
  • I can write expressions using arithmetic, concatenation, and assignment operators.
  • I understand operator precedence and know when to use parentheses.
  • I can build a string using a template literal and embed an expression with ${}.
  • I can define a function with a name, parameters, and a body.
  • I can call a function and explain why defining a function does not run it.
  • I can explain parameters, arguments, and return values.
Skills
  • I can write a function that accepts input and returns a calculated or formatted result.
  • I use camelCase and descriptive names for variables and functions.
  • I can trace a small JavaScript program by hand and correctly predict its output.
  • I can recognize and fix the common beginner mistakes covered in this chapter.
Preview — Chapter 21
Events and User Interaction

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.

MGU Library Connection
  • Web Development: HTML, CSS, and JavaScript — Appendix G: JavaScript Browser Reference
  • Web Development: HTML, CSS, and JavaScript — Appendix M: Glossary
  • Companion resource: JavaScript Syntax Quick Reference
  • Companion resource: DOM Selection Guide (preview for Chapter 22)
  • Companion resource: Event Listener Guide (preview for Chapter 21)
  • Next section: Chapter 21 — Events and User Interaction