JavaScript 101
Make your pages interactive. Buttons that do things, menus that open, text that changes: that is all JavaScript. You are about to make things move.
What is JavaScript?
JavaScript (JS) is the programming language of the web. HTML gives you structure, CSS gives you style, and JavaScript gives you behaviour.
Every interactive thing on a website, from a button that shows a menu, to a form that validates before submitting, a countdown timer, or a photo gallery, is powered by JavaScript.
<script> tag or a separate .js file.<!-- Inline in HTML --> <script> alert("Hello from JavaScript!"); </script> <!-- External file (better) --> <script src="script.js"></script>
Variables
A variable is a labelled box that stores a value. You can put a number, text, or anything else in it.
let name = "Sarah"; // a string (text) let age = 25; // a number let isLoggedIn = true; // a boolean (true/false) // const = cannot be changed after assignment const siteName = "My Site"; console.log(name); // prints "Sarah" in browser console console.log("Hello, " + name + "!"); // "Hello, Sarah!"
Live Demo
Functions
A function is a reusable block of code. You define it once and run it as many times as you want.
// Define a function function greet(name) { return "Hello, " + name + "!"; } // Call it console.log(greet("Alex")); // "Hello, Alex!" console.log(greet("Sam")); // "Hello, Sam!" // Arrow function (shorter syntax) const double = (n) => n * 2; console.log(double(5)); // 10
Conditions (if/else)
JavaScript can make decisions using if statements. If a condition is true, run this code. Otherwise, run that code.
let score = 75; if (score >= 90) { console.log("A grade!"); } else if (score >= 60) { console.log("Pass"); } else { console.log("Try again"); }
Live Demo: guess checker
The DOM
The DOM (Document Object Model) is how JavaScript sees your HTML. Every element on the page is an object you can access, change, add, or remove.
// Select an element const title = document.getElementById("main-title"); const btn = document.querySelector(".my-button"); // Change the text title.textContent = "New title!"; // Change the style title.style.color = "red"; // Add/remove a CSS class title.classList.add("active"); title.classList.remove("active"); title.classList.toggle("visible");
Events
Events are things that happen: a button click, a key press, a mouse hover. You can listen for events and run code when they happen.
const btn = document.getElementById("myBtn"); btn.addEventListener("click", function() { alert("Button clicked!"); }); // Shorthand with arrow function btn.addEventListener("click", () => { alert("Clicked!"); });
Build Something!
Let's build a real mini app, a to-do list. Type a task, press Add, and it appears on screen. This uses everything you have learned.