JavaScript โ Complete Beginner Tutorial
6 modules ยท 18 examples ยท Click โถ Run on any example to see the output
๐ก How to use this page
Read the explanation, study the code, then hit โถ Run to see the output.
Variables & Data Types
A variable is a named container for storing a value. In modern JavaScript we use "const" when the value will never change, and "let" when it might change. You will rarely use "var" โ it is the old way and has quirks best avoided.
let, const and Data Types
JavaScript has several types of data: text (called strings, always in quotes), numbers, booleans (true/false), and a special value called null that means "nothing on purpose". Use const for things that stay the same, let for things that change.
// const โ value will never change
const siteName = "CodeLearn Pro";
const pi = 3.14159;
// let โ value can change later
let score = 0;
let isLoggedIn = false;
// Types of data
const playerName = "Alice"; // String (text)
const lives = 3; // Number
const gameOver = false; // Boolean
const middleName = null; // null (no value)
console.log(playerName);
console.log(lives);
console.log(gameOver);
console.log(typeof playerName); // "typeof" tells you the type
console.log(typeof lives);
console.log(typeof gameOver);Use const by default. Only switch to let when you know the value will change (like a counter or a flag that toggles). This makes your code easier to understand.
Strings & Template Literals
Strings are text values. You can join them together (called concatenation) using the + sign, but the modern and cleaner way is template literals โ backtick quotes that let you drop variables directly into text using ${}.
const firstName = "Alice";
const lastName = "Smith";
const age = 25;
// Old way: joining with +
console.log("Hello, " + firstName + " " + lastName + "!");
// Modern way: template literals (use backticks, not quotes)
console.log(`Hello, ${firstName} ${lastName}!`);
console.log(`You are ${age} years old.`);
console.log(`Next year you will be ${age + 1}.`);
// Useful string methods
const message = " Hello World ";
console.log(message.trim()); // Remove spaces
console.log(message.trim().toLowerCase());
console.log(message.trim().toUpperCase());
console.log(message.trim().length); // How many characters
console.log(message.trim().includes("World")); // Does it contain?
console.log(message.trim().replace("World", "JavaScript"));Template literals use backtick characters (`) โ the key in the top-left of your keyboard, next to the 1. The ${} part is called an "expression slot" โ anything inside it gets converted to text.
console.log() โ Your Best Friend
console.log() prints values to the browser console (press F12 to open it). It is the main tool for seeing what your code is doing and finding bugs. You can log anything โ text, numbers, variables, results of expressions.
// Log a single value
console.log("Hello!");
// Log multiple values at once
console.log("Name:", "Bob", "| Age:", 30);
// Log the result of maths
console.log(10 + 5);
console.log(100 / 4);
console.log(2 ** 8); // 2 to the power of 8
// Log a condition result
const temperature = 32;
console.log(temperature > 30); // true
console.log(temperature === 32); // true (exact match)
console.log(temperature === "32"); // false (different type!)
// Using console.log to debug
let total = 0;
total = total + 10;
console.log("After adding 10:", total);
total = total * 2;
console.log("After doubling:", total);Open your browser console with F12 (or right-click โ Inspect โ Console). This is where console.log() output appears in real life. Every professional developer keeps it open while coding.
Operators & Conditions
Conditions let your program make decisions โ "if this is true, do this, otherwise do that." JavaScript uses curly braces {} to group the code that belongs to each branch. The === operator is the safe way to compare โ it checks both value AND type.
if / else if / else
if runs a block of code when a condition is true. else runs when it is false. else if lets you check multiple conditions in order. The first one that is true runs โ the rest are skipped.
const hour = 14; // 2 PM in 24-hour time
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
// ---
const score = 73;
if (score >= 80) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else if (score >= 60) {
console.log("Grade: C");
} else if (score >= 50) {
console.log("Grade: D โ just passed");
} else {
console.log("Grade: F โ try again");
}
// ---
// Ternary: shorthand for simple if/else
// condition ? "if true" : "if false"
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
console.log("Status:", status);The ternary operator (? :) is a one-liner if/else. Read it as: "Is age >= 18? If yes, use Adult. If no, use Minor." Only use it for simple, short decisions โ complex logic should still use a full if/else.
=== vs == and Logical Operators
JavaScript has TWO equality operators โ always use ===. The triple equals checks value AND type. The double == tries to convert types first, which causes surprising bugs. Logical operators &&, || and ! combine conditions.
// === checks value AND type (always use this!)
console.log(5 === 5); // true โ
console.log(5 === "5"); // false โ
(number vs string)
console.log(5 === 6); // false โ
// == converts types first โ AVOID this
console.log(5 == "5"); // true โ ๏ธ surprise!
console.log(0 == false); // true โ ๏ธ surprise!
console.log("" == false); // true โ ๏ธ surprise!
console.log("---");
// Logical operators
const isAdult = true;
const hasTicket = true;
const isBanned = false;
// && means AND โ both must be true
console.log(isAdult && hasTicket); // true
console.log(isAdult && isBanned); // false
// || means OR โ at least one must be true
console.log(isBanned || hasTicket); // true
console.log(isBanned || !isAdult); // false (!isAdult = false)
// ! means NOT โ flips true/false
console.log(!isBanned); // true
console.log(!isAdult); // false
// Real example
if (isAdult && hasTicket && !isBanned) {
console.log("Welcome to the event!");
} else {
console.log("Sorry, you cannot enter.");
}Rule: ALWAYS use === instead of ==. The triple equals never surprises you. The double == has a long list of weird conversion rules that trip up every beginner (and many professionals).
Loops
Loops repeat code automatically. Instead of writing console.log() ten times, you write it once inside a loop and tell the loop to run 10 times. JavaScript has several loop types โ the for loop is the most common.
for Loops
The classic for loop has three parts in the parentheses: start (let i = 0), stop condition (i < 5), and step (i++). i++ means "add 1 to i". The loop runs as long as the condition is true.
// Basic for loop โ count from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("Count:", i);
}
console.log("---");
// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
console.log("---");
// Loop through an array
const colours = ["red", "green", "blue"];
for (let i = 0; i < colours.length; i++) {
console.log(i, "โ", colours[i]);
}
console.log("---");
// for...of โ cleaner way to loop arrays
for (const colour of colours) {
console.log("Colour:", colour);
}for...of is the modern, cleaner way to loop through arrays when you do not need the index number. If you need the index, use the classic for loop or the array .forEach() method.
while Loops & break / continue
A while loop keeps running as long as its condition is true. Use break to exit a loop early, and continue to skip the current step and jump to the next one.
// while loop
let countdown = 5;
while (countdown > 0) {
console.log(countdown + "...");
countdown--; // countdown = countdown - 1
}
console.log("Blast off! ๐");
console.log("---");
// break โ stop the loop early
for (let i = 1; i <= 10; i++) {
if (i === 6) {
console.log("Found 6! Stopping.");
break;
}
console.log(i);
}
console.log("---");
// continue โ skip this step, go to next
for (let i = 1; i <= 8; i++) {
if (i % 2 === 0) continue; // skip even numbers
console.log(i);
}i++ is shorthand for i = i + 1. Similarly, i-- subtracts 1, i += 5 adds 5, and i *= 2 doubles it. These shorthand operators are used constantly in JavaScript.
Functions
Functions are reusable blocks of code. You write the logic once and call it as many times as you need. JavaScript has two main ways to write functions โ the classic "function" keyword and the modern "arrow function" (=>). Both do the same thing.
Regular Functions
Use the function keyword, give it a name, list any parameters (inputs) in the parentheses, and write the code in curly braces. Use return to send a value back to whoever called the function.
// Function with no parameters
function sayHello() {
console.log("Hello, World!");
}
sayHello(); // Call it
sayHello(); // Call it again
console.log("---");
// Function with parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
greet("Bob");
greet("Charlie");
console.log("---");
// Function that returns a value
function add(a, b) {
return a + b;
}
const result = add(10, 5);
console.log("10 + 5 =", result);
console.log("3 + 7 =", add(3, 7));
// Use the return value in calculations
const total = add(100, 50) * 2;
console.log("Total:", total);return stops the function immediately and sends the value back. Code after return in the same function never runs. A function without return automatically returns "undefined".
Arrow Functions =>
Arrow functions are a shorter way to write functions โ especially useful for small, single-purpose functions. They use => instead of the function keyword. If the function body is just one expression, you can skip the curly braces and return keyword.
// Regular function
function square(n) {
return n * n;
}
// Same thing as an arrow function
const squareArrow = (n) => {
return n * n;
};
// Even shorter โ one line, no {} or return needed
const squareShort = (n) => n * n;
console.log(square(4)); // 16
console.log(squareArrow(4)); // 16
console.log(squareShort(4)); // 16
console.log("---");
// More examples
const double = (n) => n * 2;
const isEven = (n) => n % 2 === 0;
const greet = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const getMax = (a, b) => a > b ? a : b;
console.log(double(7));
console.log(isEven(8));
console.log(greet("Alice"));
console.log(add(3, 4));
console.log(getMax(10, 25));Arrow functions with a single parameter can drop the parentheses: n => n * 2. But with zero or two+ parameters you need them: () => "hello" or (a, b) => a + b. When starting out, always keep the parentheses to stay consistent.
Default Parameters & Scope
You can give parameters a default value that is used when no argument is passed in. Scope means where a variable is accessible โ variables declared inside a function only exist inside that function.
// Default parameters
function greet(name = "stranger", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // Both defaults
console.log(greet("Alice")); // greeting is default
console.log(greet("Bob", "Good day")); // No defaults used
console.log("---");
// Scope โ where variables live
const globalMessage = "I exist everywhere";
function showScope() {
const localMessage = "I only exist in this function";
console.log(globalMessage); // โ
Can read global
console.log(localMessage); // โ
Can read local
}
showScope();
console.log(globalMessage); // โ
Works
// console.log(localMessage); // โ Would crash โ doesn't exist here
console.log("---");
// Functions do not change the original variable
function addTen(number) {
number = number + 10; // only changes the local copy
return number;
}
let myScore = 50;
const newScore = addTen(myScore);
console.log("Original:", myScore); // Still 50!
console.log("New:", newScore); // 60Variables declared with const or let inside a function are "local" โ they are created when the function runs and destroyed when it ends. This is intentional: it keeps functions independent and prevents them from accidentally affecting each other.
Arrays & Objects
Arrays store ordered lists of items. Objects store labelled data as key-value pairs โ like a profile card with a name, age and city. Together they are the backbone of almost every JavaScript program you will ever write.
Arrays โ Creating & Accessing
Arrays use square brackets []. Items are separated by commas. Positions start at 0. You can mix types in one array, though usually you keep them the same type.
// Creating arrays
const fruits = ["apple", "banana", "cherry"];
const scores = [95, 82, 71, 88, 60];
const mixed = ["hello", 42, true, null]; // mixed (unusual)
// Accessing by index (starts at 0)
console.log(fruits[0]); // First item
console.log(fruits[1]); // Second item
console.log(fruits[fruits.length - 1]); // Last item
console.log("---");
// Common methods
fruits.push("mango"); // Add to end
console.log("After push:", fruits);
fruits.pop(); // Remove from end
console.log("After pop:", fruits);
fruits.unshift("kiwi"); // Add to beginning
console.log("After unshift:", fruits);
console.log("Length:", fruits.length);
console.log("Includes banana?", fruits.includes("banana"));
console.log("---");
// Slice: get a portion (does NOT change original)
const top3 = scores.slice(0, 3);
console.log("Top 3:", top3);
console.log("All scores:", scores); // Unchangedpush() and pop() work on the END of the array. unshift() and shift() work on the BEGINNING. push/pop are faster and more commonly used.
Powerful Array Methods โ map, filter, find
JavaScript arrays have built-in methods that transform data without needing a manual for loop. map() transforms every item. filter() keeps only matching items. find() returns the first match. These are used constantly in real apps.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
// map โ transform every item, returns new array
const doubled = numbers.map((n) => n * 2);
console.log("Doubled:", doubled);
const asStrings = numbers.map((n) => "Item " + n);
console.log("As strings:", asStrings);
console.log("---");
// filter โ keep only items that pass a test
const evens = numbers.filter((n) => n % 2 === 0);
console.log("Evens:", evens);
const bigOnes = numbers.filter((n) => n > 5);
console.log("Over 5:", bigOnes);
console.log("---");
// find โ get the FIRST item that matches
const firstEven = numbers.find((n) => n % 2 === 0);
console.log("First even:", firstEven);
// reduce โ boil down to one value
const sum = numbers.reduce((total, n) => total + n, 0);
console.log("Sum:", sum);
console.log("---");
// Chaining โ combine methods
const result = numbers
.filter((n) => n % 2 === 0) // keep evens: [2,4,6,8]
.map((n) => n * 10); // multiply by 10
console.log("Evens ร 10:", result);map() and filter() always return a NEW array โ they never change the original. This is called "immutability" and makes bugs much easier to track down.
Objects โ Key-Value Data
An object stores related data under named labels (called keys). Think of it as a profile card. Use dot notation (person.name) or bracket notation (person["name"]) to access values.
// Creating an object
const student = {
name: "Alice",
age: 20,
grade: "A",
city: "Cape Town",
isEnrolled: true,
};
// Accessing values
console.log(student.name);
console.log(student.age);
console.log(`${student.name} is in grade ${student.grade}`);
// Updating and adding
student.age = 21; // Update existing
student.email = "alice@example.com"; // Add new key
console.log(student.age);
console.log(student.email);
console.log("---");
// Object methods (functions inside objects)
const calculator = {
brand: "CodeCalc",
add: (a, b) => a + b,
multiply: (a, b) => a * b,
};
console.log(calculator.brand);
console.log(calculator.add(5, 3));
console.log(calculator.multiply(4, 7));
console.log("---");
// Loop through an object
for (const key in student) {
console.log(`${key}: ${student[key]}`);
}Objects are everywhere in JavaScript โ every DOM element, every API response, every React component has objects. Getting comfortable with them is one of the most important JavaScript skills.
DOM & Events
The DOM (Document Object Model) is how JavaScript talks to your HTML page. You can find elements, change their text or style, and respond to user actions like clicks and typing. This is where JavaScript becomes truly powerful โ your page becomes interactive.
Finding & Changing HTML Elements
querySelector() finds the first element that matches a CSS selector. Once you have it, you can change its text, HTML, or style. Think of it like grabbing an element with a remote control and then editing it live.
// In a real page, you would have this HTML:
// <h1 id="title">Welcome</h1>
// <p class="intro">Hello world</p>
// <button id="btn">Click me</button>
// Find elements
const title = document.querySelector("#title"); // by ID
const intro = document.querySelector(".intro"); // by class
const btn = document.querySelector("#btn"); // by ID
const allParas = document.querySelectorAll("p"); // ALL <p> tags
// Change text content
title.textContent = "Hello, JavaScript!";
intro.textContent = "I was changed by JS!";
// Change HTML inside an element
title.innerHTML = "<em>Hello</em>, JavaScript!";
// Change styles
title.style.color = "blue";
title.style.fontSize = "2rem";
intro.style.backgroundColor = "yellow";
// Add or remove CSS classes
title.classList.add("highlight");
title.classList.remove("old-style");
title.classList.toggle("active"); // adds if absent, removes if present
console.log("Title text:", title.textContent);
console.log("All paragraphs found:", allParas.length);#id selects by ID (should be unique on the page). .class selects by class (can match many elements). querySelectorAll() returns ALL matches โ use a regular for loop or forEach() to go through them.
Event Listeners โ Reacting to Clicks
addEventListener() watches for something to happen on an element โ a click, a key press, moving the mouse. When it happens, it runs your function. This is how you make interactive buttons, forms, and menus.
// In a real page, you would have this HTML:
// <button id="btn">Click me</button>
// <p id="counter">0</p>
// <input id="nameInput" placeholder="Type your name" />
// <p id="greeting"></p>
const btn = document.querySelector("#btn");
const counter = document.querySelector("#counter");
const nameInput = document.querySelector("#nameInput");
const greeting = document.querySelector("#greeting");
// Click event โ runs when the button is clicked
let clickCount = 0;
btn.addEventListener("click", () => {
clickCount++;
counter.textContent = clickCount;
console.log("Button clicked! Count:", clickCount);
// Change button colour after 5 clicks
if (clickCount >= 5) {
btn.style.backgroundColor = "green";
btn.textContent = "Thanks! ๐";
}
});
// Input event โ runs as the user types
nameInput.addEventListener("input", () => {
const name = nameInput.value;
if (name.length > 0) {
greeting.textContent = `Hello, ${name}!`;
} else {
greeting.textContent = "";
}
console.log("User typed:", name);
});
// Mouseover event
btn.addEventListener("mouseover", () => {
btn.style.opacity = "0.8";
});
btn.addEventListener("mouseout", () => {
btn.style.opacity = "1";
});The function you pass to addEventListener is called a "callback" โ it does not run straight away. It waits until the event happens, then runs. This "wait and react" pattern is everywhere in JavaScript.
Creating & Adding New Elements
You can create brand new HTML elements with JavaScript and add them to the page. This is how dynamic lists, cards, and content get added without refreshing the page.
// Create a new element
const newPara = document.createElement("p");
newPara.textContent = "I was created by JavaScript!";
newPara.style.color = "green";
// Add it to the page
document.body.appendChild(newPara);
// Create a list dynamically
const names = ["Alice", "Bob", "Charlie", "Diana"];
const list = document.createElement("ul");
names.forEach((name) => {
const item = document.createElement("li");
item.textContent = name;
list.appendChild(item);
});
document.body.appendChild(list);
// Remove an element
const oldTitle = document.querySelector("#old-heading");
if (oldTitle) {
oldTitle.remove();
}
console.log("New elements added to the page!");
console.log("List has", list.children.length, "items");createElement() creates the element but does not add it to the page yet. appendChild() or append() places it inside another element. This two-step pattern lets you set up the element first, then place it exactly where you want.
You finished the JavaScript tutorial!
You now know variables, conditions, loops, functions, arrays, objects, and how to make pages interactive with the DOM. These are the skills every web developer uses every single day.