Lesson progress: 0%

JavaScript Fundamentals

Make your pages respond. Learn the core of JavaScript, then use it to build something interactive.

BeginnerModule 0560 minutes

What you will learn

  • What JavaScript does and how to add it to a page.
  • Variables, data types, operators, and comparisons.
  • Conditions, loops, and functions.
  • How to select and change page elements with the DOM.
  • How to react to clicks and typing with events.
  • How to handle errors and debug with the browser console.

Each JavaScript example has a Try it button that loads it into the playground, so you can run it and change it. Your code runs in an isolated sandbox that cannot touch this page.

Part 1

What JavaScript does

A website has three layers. JavaScript is the one that makes things happen: updating text, responding to clicks, checking a form, or running a game. It runs inside the browser, so no installation is needed. (Despite the name, it is unrelated to Java.)

HTML

Structure and content.

CSS

Appearance and layout.

JavaScript

Behavior and logic.

Part 2

Connecting JavaScript to HTML

Put a script element at the end of the body, so the page elements exist before your code looks for them. Use an external file for real projects.

index.html
<body>
  <h1 id="title">Hello</h1>

  <script src="app.js"></script>
</body>
app.js
console.log("Hello from JavaScript!");

Output (in the console)Hello from JavaScript!

You can also write code directly between <script> and </script>, or add defer to a script in the head so it waits for the page.

Common mistake: placing the script above the elements it uses. The code runs before they exist, and you get null.

Part 3

Variables: let and const

A variable is a named box that stores a value.

app.js
const siteName = "CODEX";
let score = 0;
score = score + 10;
console.log(siteName, score);
  1. const siteName = "CODEX"; creates a variable that can never be reassigned.
  2. let score = 0; creates a variable that can change later.
  3. score = score + 10; reads the old value, adds 10, and stores the result.
  4. console.log(...) prints the values to the console.

OutputCODEX 10

Rule of thumb: use const by default, and let only when the value must change. Name variables in camelCase, like totalScore.

Common mistake: reassigning a const. siteName = "X"; throws "Assignment to constant variable".

Part 4

Strings, numbers, booleans, arrays, and objects

app.js
const name = "Sam";                    // string: text
const age = 14;                        // number
const isStudent = true;                // boolean: true or false
const hobbies = ["art", "football"];   // array: an ordered list
const person = { name: "Sam", age: 14 }; // object: named values

console.log(hobbies[0]);
console.log(hobbies.length);
console.log(person.name);
console.log(typeof age);

Outputart
2
Sam
number

  1. hobbies[0] reads the first array item. Counting starts at 0.
  2. hobbies.length is the number of items.
  3. person.name reads a property of an object using a dot.
  4. typeof tells you which type a value is.

Common mistake: expecting the first item at [1]. Arrays start at index 0, so the last item is at length - 1.

Part 5

Operators and comparisons

app.js
console.log(7 + 3);        // add
console.log(7 % 3);        // remainder
console.log(5 === 5);      // equal value and type
console.log(5 === "5");    // different types
console.log(5 !== 3);      // not equal
console.log(10 > 3 && 2 > 5);  // AND: both must be true
console.log(10 > 3 || 2 > 5);  // OR: one is enough
console.log("5" + 3);      // string joining

Output10
1
true
false
true
false
true
53

Use === and !== for comparisons. They check value and type, which avoids surprises. Combine conditions with && (and), || (or), and ! (not).

Common mistake: writing = when you mean ===. A single = assigns a value, it does not compare.

Part 6

Conditional statements

Conditions let your code choose. JavaScript checks them from top to bottom and runs the first one that is true.

app.js
const score = 72;

if (score >= 90) {
  console.log("Excellent");
} else if (score >= 60) {
  console.log("Good");
} else {
  console.log("Keep practicing");
}

OutputGood

The first test fails (72 is not 90 or more), the second passes, so "Good" prints and the else is skipped. Change score to try the other branches.

Common mistake: putting conditions in the wrong order. If you tested score >= 60 first, a score of 95 would print "Good".

Part 7

Loops: for and while

Loops repeat code. Use for when you know how many times, and while when you repeat until something changes.

app.js
for (let i = 1; i <= 3; i++) {
  console.log("Round " + i);
}

let countdown = 3;
while (countdown > 0) {
  console.log(countdown);
  countdown--;
}
console.log("Go!");

OutputRound 1
Round 2
Round 3
3
2
1
Go!

  1. let i = 1 sets the start. i <= 3 is the condition that keeps the loop going. i++ adds 1 each time.
  2. The while loop runs as long as countdown > 0. countdown-- subtracts 1 each round.

Common mistake: an infinite loop. If you forget countdown--, the condition never becomes false. Also watch for off-by-one errors, like < versus <=.

Part 8

Functions, parameters, return values, and scope

A function is a reusable block of code. Parameters are its inputs, and return sends back an output.

app.js
function add(a, b) {
  const total = a + b;
  return total;
}

const result = add(2, 3);
console.log(result);
console.log(add(10, 5));

Output5
15

  1. function add(a, b) defines a function with two parameters.
  2. return total; hands the value back and ends the function.
  3. add(2, 3) calls it with the arguments 2 and 3.

Scope: a variable created inside a function or block only exists there.

app.js
function demo() {
  const secret = 42;
  console.log(secret);
}
demo();
console.log(secret);

Output42
Uncaught ReferenceError: secret is not defined

Common mistake: forgetting return, which makes the function give back undefined, or writing add instead of add(2, 3) so it never runs.

Part 9

The DOM: selecting and changing elements

The browser turns your HTML into a tree of objects called the DOM. JavaScript can find elements in it and change them.

index.html
<h1 id="title">Hello</h1>
<ul id="list"></ul>
app.js (page)
const title = document.getElementById("title");
title.textContent = "Hello, CODEX!";
title.classList.add("highlight");

const list = document.getElementById("list");
const item = document.createElement("li");
item.textContent = "First item";
list.appendChild(item);
  1. getElementById("title") finds the element with that id. querySelector(".card") finds by any CSS selector.
  2. textContent changes the text. classList.add, remove, and toggle change CSS classes.
  3. createElement makes a new element, and appendChild puts it on the page.

Result on the pageThe heading now reads "Hello, CODEX!" and the list shows one item.

Common mistake: using innerHTML with text a visitor typed. It can inject harmful code. Prefer textContent.

Part 10

Events and event listeners

An event is something that happens: a click, a key press, typing in an input. An event listener runs a function when it does.

index.html
<button id="btn">Click me</button>
<p id="out"></p>
app.js (page)
const btn = document.getElementById("btn");
const out = document.getElementById("out");
let count = 0;

btn.addEventListener("click", function () {
  count = count + 1;
  out.textContent = "Clicks: " + count;
});

Result on the pageEach click updates the text: Clicks: 1, Clicks: 2, and so on.

This exact example is already loaded in the playground below. Run it and click the button in the preview.

Common mistake: writing addEventListener("click", sayHi()). The parentheses call the function immediately. Pass sayHi without them.

Part 11

Error handling and debugging

Errors are normal, and they are useful: the message tells you what went wrong and often where. Use try and catch to handle problems without crashing, and throw to raise your own.

app.js
function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

try {
  console.log(divide(10, 2));
  console.log(divide(5, 0));
} catch (err) {
  console.log("Error: " + err.message);
}

Output5
Error: Cannot divide by zero

Debugging with the browser console

  • Open the console. Press F12 (or right-click, then Inspect) and choose the Console tab. Errors appear in red with a file name and line number.
  • Read the message. "x is not defined" usually means a typo or a wrong scope. "Cannot read properties of null" means an element was not found.
  • Print values. Add console.log(variable) to see what the code is really doing.
  • Check spelling and case. myVar and myvar are different names.
  • Change one thing at a time, then run again.

Practice

JavaScript playground

Edit the HTML and JavaScript, then press Run. Output from console.log and any errors appear in the console below. Your code runs in a sandboxed frame, isolated from this page.

Output preview

preview
Console

Challenges

Three coding challenges

Each one gets harder. Write the function, then press Check to run it against tests. Passed: 0 of 3.

Final project

Build an interactive to-do list

Finish the starter below so that your list can add, complete, and remove tasks. Follow the numbered TODO comments, press Run, and test it in the preview. Stuck? Load the finished example and compare it with yours line by line.

Your to-do list

to-do list
Console

Tick each item when it works in your preview

Stretch goal: show how many tasks are left, or build a click counter instead using the example in Part 10.

Knowledge check

Test what you learned

Finish Module 05

Ran the examples, solved the challenges, and built your list? Mark the lesson complete. Progress is saved in this browser only.