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.
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.
| Browser | JS Engine |
|---|---|
| Chrome, Edge | V8 |
| Firefox | SpiderMonkey |
| Safari | JavaScriptCore |
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
letandconst?
constmeans the variable can never be reassigned.letmeans it can. Useconstby default and only switch toletwhen 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 XPThe 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);
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:
| Event | Fires when... |
|---|---|
click | User clicks an element |
input | User types in a text field |
submit | A form is submitted |
mouseover | Cursor enters an element |
keydown | A key is pressed |
scroll | The page is scrolled |
load | The page finishes loading |
Build a counter
50 XPPractical 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
.jsfile 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 XPFrom 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
constby default,letwhen you need to reassign, nevervar - 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 elementsfetch()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?