O
Octo
O
Octo
CoursesPricingDashboardPrivacyTerms

© 2026 Octo

Web Development
1How Websites Work2HTML Fundamentals3CSS Fundamentals4JavaScript Fundamentals5Building Your First Website
Module 4

JavaScript Fundamentals

Learn JavaScript basics — variables, functions, DOM manipulation, events, and API calls. The language that makes webpages interactive and powers the modern web.

The language that was built in 10 days

In May 1995, Netscape needed a scripting language for their browser. They gave the job to Brendan Eich. He had 10 days. The result was JavaScript — a language thrown together under absurd pressure that became the most widely used programming language on Earth.

It was originally meant for simple things: validating form fields, making buttons change color, showing alert boxes. Nobody imagined it would eventually power server backends, mobile apps, desktop applications, game engines, and machine learning models.

Today, JavaScript runs on every smartphone, laptop, and tablet in the world. Every browser speaks it natively. Learning JavaScript doesn't just make your web pages interactive — it gives you access to the single most ubiquitous computing platform ever built.

98%Of websites use JavaScript

12yrMost popular language (Stack Overflow)

17MJavaScript developers worldwide

Where JavaScript runs

Unlike HTML and CSS, which the browser just reads, JavaScript is executed. The browser has a built-in JavaScript engine that runs your code.

BrowserJS Engine
Chrome, EdgeV8
FirefoxSpiderMonkey
SafariJavaScriptCore

You can run JavaScript right now. Open your browser, press F12 (or Cmd+Option+I on Mac), click the Console tab, and type:

alert("Hello from JavaScript!");

Press Enter. That pop-up? That's JavaScript executing in real-time.

Variables: storing data

Variables are containers that hold values. JavaScript has three ways to declare them:

let name = "Sarah";       // Can be reassigned later
const age = 28;           // Cannot be reassigned (constant)
var old = "avoid this";   // Old syntax — use let or const instead

✗ Without AI

  • ✗The value will change later
  • ✗Loop counters
  • ✗User input storage
  • ✗Temporary calculations

✓ With AI

  • ✓The value should never change
  • ✓Configuration values
  • ✓Function references
  • ✓DOM element references

Data types in JavaScript:

// Strings (text)
let greeting = "Hello, world!";

// Numbers (integers and decimals)
let price = 19.99;
let quantity = 3;

// Booleans (true or false)
let isLoggedIn = true;

// Arrays (ordered lists)
let colors = ["red", "green", "blue"];

// Objects (key-value pairs)
let user = {
  name: "Sarah",
  age: 28,
  isPremium: true
};

There Are No Dumb Questions

What's the difference between let and const?

const means the variable can never be reassigned. let means it can. Use const by default and only switch to let when you actually need to reassign. This makes your code more predictable.

Is JavaScript the same as Java?

No. They're completely different languages. JavaScript was named "JavaScript" for marketing reasons — Java was popular in 1995 and Netscape wanted to ride the hype. The joke in the community: "Java is to JavaScript as car is to carpet."

Functions: reusable blocks of code

Functions let you write code once and run it whenever you need it:

// Declaring a function
function greet(name) {
  return "Hello, " + name + "!";
}

// Calling the function
let message = greet("Sarah");
console.log(message);  // "Hello, Sarah!"

// Arrow function (modern syntax)
const multiply = (a, b) => a * b;
console.log(multiply(5, 3));  // 15

Functions take parameters (inputs) and return values (outputs). They're the building blocks of every JavaScript program.

// A practical function: calculate the total with tax
function calculateTotal(price, taxRate) {
  const tax = price * taxRate;
  const total = price + tax;
  return total;
}

const orderTotal = calculateTotal(49.99, 0.08);
console.log(orderTotal);  // 53.99

⚡

Write your first function

25 XP
Open your browser console (F12 > Console tab) and write a function called `introduce` that takes two parameters: `name` and `job`. It should return a string like: "Hi, I'm Sarah and I'm a designer." Test it by calling `introduce("Sarah", "designer")` and verify the output. Bonus: Write an arrow function version of the same function.

The DOM: JavaScript meets HTML

The DOM (Document Object Model) is how JavaScript interacts with your HTML page. The browser converts your HTML into a tree of objects that JavaScript can read and modify.

// Select elements
const heading = document.querySelector("h1");
const allButtons = document.querySelectorAll("button");
const nav = document.getElementById("main-nav");

// Read content
console.log(heading.textContent);  // Gets the text inside the <h1>

// Change content
heading.textContent = "New Title!";

// Change styles
heading.style.color = "blue";
heading.style.fontSize = "48px";

// Add/remove CSS classes
heading.classList.add("highlighted");
heading.classList.remove("old-class");
heading.classList.toggle("active");

// Create new elements
const newParagraph = document.createElement("p");
newParagraph.textContent = "I was created by JavaScript!";
document.body.appendChild(newParagraph);

HTML Document
DOM Tree (Browser)
JavaScript
Updated Page
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

🔑querySelector is your best friend
`document.querySelector()` uses CSS selectors to find elements. If you can select it in CSS, you can select it in JavaScript. `querySelector(".card")` finds the first element with class "card." `querySelectorAll(".card")` finds ALL of them.

Events: responding to user actions

Events are how you make pages interactive. When a user clicks, types, scrolls, or hovers — that's an event. JavaScript can listen for events and respond:

// Click event
const button = document.querySelector("#subscribe");
button.addEventListener("click", function() {
  alert("Thanks for subscribing!");
});

// Input event (fires as user types)
const searchBox = document.querySelector("#search");
searchBox.addEventListener("input", function(event) {
  console.log("User typed:", event.target.value);
});

// Keyboard event
document.addEventListener("keydown", function(event) {
  if (event.key === "Escape") {
    closeModal();
  }
});

Common events:

EventFires when...
clickUser clicks an element
inputUser types in a text field
submitA form is submitted
mouseoverCursor enters an element
keydownA key is pressed
scrollThe page is scrolled
loadThe page finishes loading

⚡

Build a counter

50 XP
Create an HTML page with: - A heading that displays a number (starting at 0) - Two buttons: one labeled "+" and one labeled "-" Write JavaScript that: 1. Increments the number when "+" is clicked 2. Decrements the number when "-" is clicked 3. Never lets the count go below 0 This is a classic first JavaScript project. Here's the HTML to start with: ```html <h1 id="count">0</h1> <button id="increment">+</button> <button id="decrement">-</button> ``` Write the JavaScript in a `<script>` tag at the bottom of your `<body>`.

Practical example: a todo list

Let's combine everything — DOM manipulation, events, and functions — into a real feature:

<input type="text" id="todo-input" placeholder="Add a task..."></callout>

<button id="add-btn">Add</button>
<ul id="todo-list"></ul>
const input = document.querySelector("#todo-input");
const addBtn = document.querySelector("#add-btn");
const list = document.querySelector("#todo-list");

function addTodo() {
  const text = input.value.trim();
  if (text === "") return;

  const li = document.createElement("li");
  li.textContent = text;

  // Click to mark as done
  li.addEventListener("click", function() {
    li.style.textDecoration = "line-through";
    li.style.color = "#999";
  });

  list.appendChild(li);
  input.value = "";      // Clear the input
  input.focus();         // Put cursor back in the input
}

addBtn.addEventListener("click", addTodo);

// Also add when pressing Enter
input.addEventListener("keydown", function(event) {
  if (event.key === "Enter") addTodo();
});

That's a functional todo list in 25 lines. No frameworks, no libraries — just plain JavaScript.

There Are No Dumb Questions

Do I need to learn a framework like React right away?

No. Frameworks are built on top of these fundamentals. If you understand DOM manipulation, events, and functions, learning React later will be dramatically easier. Many professional projects still use plain JavaScript without any framework.

Where do I put my JavaScript?

In an external .js file linked at the bottom of your HTML body: <script src="script.js"></script>. Placing it at the bottom ensures the HTML is fully loaded before your JavaScript tries to access elements.

APIs: getting data from the internet

JavaScript can fetch data from external services using APIs (Application Programming Interfaces). This is how weather apps, news feeds, and stock tickers work.

// Fetch data from a public API
fetch("https://api.github.com/users/octocat")
  .then(response => response.json())
  .then(data => {
    console.log(data.name);        // "The Octocat"
    console.log(data.public_repos); // 8
  });

// Modern async/await syntax (cleaner)
async function getUser() {
  const response = await fetch("https://api.github.com/users/octocat");
  const data = await response.json();
  console.log(data.name);
}

getUser();

fetch() sends an HTTP request to a URL (just like your browser does for web pages)

response.json() converts the response from raw text into a JavaScript object

async/await lets you write asynchronous code that reads like normal code

Public APIs are everywhere: weather data, stock prices, Pokemon info, random quotes, country data

⚡

Fetch from a real API

25 XP
Open your browser console and run this code: ```javascript fetch("https://api.github.com/users/octocat") .then(r => r.json()) .then(data => console.log(data)); ``` Explore the returned object. How many public repos does `octocat` have? What's the value of `avatar_url`? Now try replacing `octocat` with your own GitHub username (if you have one) or any other username.

From 10 days to the entire world

Brendan Eich's hastily assembled scripting language shouldn't have worked. It had quirks and inconsistencies that developers still joke about (try typeof null in your console — it says "object"). But JavaScript survived because it was in the right place at the right time: inside every browser on every computer. That same universal reach is now your advantage. The variables, functions, DOM manipulation, events, and API calls you've learned in this module are the foundation of every interactive website, every web application, and every modern front-end framework. In the next module, you'll put it all together and build a complete website.

Key takeaways

  • JavaScript is the only programming language that runs natively in every browser
  • Use const by default, let when you need to reassign, never var
  • The DOM is JavaScript's interface to the HTML page — select, modify, create, delete elements
  • Events (click, input, keydown, submit) make pages interactive
  • querySelector() uses CSS selectors to find DOM elements
  • fetch() calls APIs and returns data from the internet
  • Functions are reusable blocks of code that take inputs and return outputs

?

Knowledge Check

1.What is the DOM?

2.What is the correct way to listen for a button click in JavaScript?

3.What is the difference between let and const?

4.What does fetch() do?

Previous

CSS Fundamentals

Next

Building Your First Website