Lesson 04

JavaScript Basics

Add logic, data, decisions, loops, and reusable functions.

This lesson

What you’ll learn

Progress

Track this lesson

Sign in to save this lesson to your learning dashboard.

Log in to track progress

JavaScript’s role

JavaScript is the behaviour layer of a website. It reacts to clicks, validates forms, updates content, fetches data, stores state, and powers interactive components.

Variables and values

Use const for bindings that should not be reassigned and let for bindings that change. Common data types include strings, numbers, booleans, arrays, objects, null, and undefined. Choose descriptive names such as completedLessons instead of x so the code explains its purpose.

Assignment and comparison

A single equals sign (=) assigns a value. Double equals (==) compares values after type coercion, which can produce surprising results. Triple equals (===) compares both value and type, so it is the safer default for application code. For example, 0 == "0" is true, while 0 === "0" is false.

Functions

Functions package logic into reusable pieces. A clear function has a focused purpose, useful inputs, and a predictable result. Prefer returning a value from a function so other parts of the program can decide how to display or use that result.

Conditionals

Conditionals let code make decisions. Use if, else if, and else to handle different states.

Arrays, objects, and iteration

Arrays store ordered lists. Objects store related properties. Websites often use arrays of objects to represent cards, products, tasks, lessons, and users. Array methods make common operations readable: use filter() to select matching items, map() to transform items, and find() to retrieve the first match.

Example code

const lessons = [
  { title: "HTML Foundations", completed: true },
  { title: "CSS Fundamentals", completed: true },
  { title: "JavaScript Basics", completed: false }
];

function calculateProgress(items) {
  const completed = items.filter((item) => item.completed);
  return Math.round((completed.length / items.length) * 100);
}

console.log(`Progress: ${calculateProgress(lessons)}%`);

Applied example: summarise task progress

This example separates calculation from display. The function receives data, returns a useful result, and can be tested independently.

const tasks = [
  { title: "Write HTML", completed: true },
  { title: "Style cards", completed: true },
  { title: "Test mobile layout", completed: false }
];

function getProgressSummary(items) {
  const completedCount = items.filter((item) => item.completed).length;
  const percent = Math.round((completedCount / items.length) * 100);

  return `${completedCount} of ${items.length} tasks complete (${percent}%)`;
}

console.log(getProgressSummary(tasks));

Guided example: how to approach this lesson

Use these steps as a practical build process. The goal is not just to read the concept, but to know exactly how to apply it in your own page.

Step 1: Store the data

Create variables, arrays, or objects that represent the information your page needs.

Step 2: Write small functions

Each function should do one clear thing, such as calculate progress or format a message.

Step 3: Connect logic to output

Once the logic works in the console, connect it to the page using the DOM.

More examples

Compare these examples carefully. The improved version shows the kind of code pattern you should aim for when building your own project.

Unclear logic

let x = 3;
let y = 10;
console.log(x / y * 100);

This works mathematically, but the variable names do not explain what the values mean.

Clear logic

const completedLessons = 3;
const totalLessons = 10;

function getProgressPercent(completed, total) {
  return Math.round((completed / total) * 100);
}

console.log(getProgressPercent(completedLessons, totalLessons));

This is easier to understand because the names explain the purpose of the data.

Before moving on

Use this checklist to make sure you understand the lesson well enough to apply it without copying blindly.

  • Are variable names descriptive?
  • Does each function have one clear job?
  • Have you tested the logic in the console?
  • Are errors visible in DevTools?

Common mistakes to avoid

  • Using var in modern code.
  • Writing one huge function.
  • Confusing =, ==, and ===: use = to assign a value, and prefer === for comparisons because it checks value and type.
  • Ignoring console errors.

Practice task

Create a progress summary for a five-item website launch checklist.

Required outcome

  • Store five task objects in an array. Each object needs a title and a boolean completed value.
  • Write one function that returns the number of completed tasks and another that returns the percentage.
  • Use a conditional to print a different message when every task is complete.
  • Test your functions in the browser console with incomplete and complete data.

Stretch goal: Use map() to create a new array containing only the task titles.