๐Ÿ”’

Sign In Required

This workbook requires a free KaliRange account.

Log In โ†’Create Account
๐Ÿ‘ถ
No install needed! Open any browser โ†’ right-click the page โ†’ Inspect โ†’ Console tab. Type JavaScript directly and press Enter. Or create an HTML file, add <script> tags, and open in browser.

Chapter 1 โ€” What is JavaScript?

HTML is the skeleton, CSS is the skin, JavaScript is the muscles โ€” it makes pages move, respond, and do things. JS runs inside the browser and also on servers (Node.js).

// Add JS to HTML โ€” three ways:

// 1. Inline (avoid โ€” hard to maintain):
<button onclick="alert('Hello!')">Click</button>

// 2. Internal script block (in <body> before closing tag):
<script>
  console.log("Hello from JS!");
</script>

// 3. External file (best โ€” separate .js file):
<script src="main.js"></script>

// Output to browser console:
console.log("Hello, World!");
console.log(42, true, [1,2,3]);   // can log multiple things
console.error("Something broke!"); // red error message
console.warn("Watch out!");        // yellow warning

// Pop-up dialogs (use sparingly):
alert("Hello!");                        // message box
let name = prompt("What's your name?"); // ask for input
let ok = confirm("Are you sure?");      // yes/no box โ†’ true/false

Chapter 2 โ€” Variables & Types

// Three ways to declare variables:
let   age = 25;      // can be reassigned โ€” use this by default
const PI  = 3.14;    // constant โ€” can NOT be reassigned
var   old = "avoid"; // old way โ€” avoid var

// Data types:
let str    = "Hello";        // String
let num    = 42;             // Number (int AND float โ€” same type)
let float  = 3.14;           // also Number
let bool   = true;           // Boolean: true or false
let nothing = null;          // null โ€” intentionally empty
let undef;                   // undefined โ€” not assigned yet
let arr  = [1, 2, 3];        // Array
let obj  = { name: "Alice" }; // Object

// Check type:
console.log(typeof "hello");  // string
console.log(typeof 42);       // number
console.log(typeof true);     // boolean
console.log(typeof null);     // object (known JS quirk!)

// Convert types:
let x = "42";
console.log(Number(x));       // 42
console.log(parseInt("42px")); // 42 (stops at first non-number)
console.log(String(123));     // "123"
console.log(Boolean(0));      // false (0, "", null, undefined โ†’ false)
console.log(Boolean(1));      // true

Chapter 3 โ€” Operators & Conditionals

// Arithmetic:
console.log(10 + 3);   // 13
console.log(10 - 3);   // 7
console.log(10 * 3);   // 30
console.log(10 / 3);   // 3.333...
console.log(10 % 3);   // 1 (remainder)
console.log(2 ** 8);   // 256 (power)

// String concatenation:
console.log("Hello" + " " + "World"); // Hello World
let name = "Uzair";
console.log(`Hello, ${name}!`);       // template literal
console.log(`2 + 2 = ${2 + 2}`);      // 2 + 2 = 4

// Comparison โ€” use === (strict) not == (loose):
console.log(5 === 5);    // true  (same value AND type)
console.log(5 === "5");  // false (different types)
console.log(5 == "5");   // true  (loose โ€” converts types, avoid!)
console.log(5 !== 3);    // true  (strict not-equal)
console.log(5 > 3);      // true

// Logical:
console.log(true && false);  // false (AND)
console.log(true || false);  // true  (OR)
console.log(!true);          // false (NOT)

// If / else if / else:
let age = 20;
if (age >= 18) {
    console.log("Adult");
} else if (age >= 13) {
    console.log("Teenager");
} else {
    console.log("Child");
}

// Ternary:
let status = age >= 18 ? "adult" : "minor";

// Switch:
let day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("Almost weekend!");
        break;
    default:
        console.log("Regular day");
}

Chapter 4 โ€” Functions

// Function declaration:
function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet("Uzair"));   // Hello, Uzair!

// Function expression:
const add = function(a, b) {
    return a + b;
};

// Arrow function (modern, preferred):
const multiply = (a, b) => a * b;       // one-liner, implicit return
const square   = x => x * x;           // single param, no brackets needed
const sayHi    = () => console.log("Hi!"); // no params

// Default parameters:
const greet2 = (name = "stranger") => `Hello, ${name}!`;
console.log(greet2());         // Hello, stranger!
console.log(greet2("Alice"));  // Hello, Alice!

// Rest parameters (any number of args):
const sum = (...nums) => nums.reduce((total, n) => total + n, 0);
console.log(sum(1, 2, 3, 4, 5));   // 15

// Immediately Invoked Function Expression (IIFE):
(function() {
    console.log("Runs immediately!");
})();

Chapter 5 โ€” Arrays & Objects

// Arrays:
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);          // apple
console.log(fruits.length);      // 3

fruits.push("mango");            // add to end
fruits.pop();                    // remove from end
fruits.unshift("grape");         // add to start
fruits.shift();                  // remove from start
console.log(fruits.includes("banana"));  // true
console.log(fruits.indexOf("banana"));   // 1
console.log(fruits.join(", "));          // apple, banana, cherry

// Array methods (most important in JS):
const nums = [1, 2, 3, 4, 5];
const doubled  = nums.map(n => n * 2);        // [2,4,6,8,10]
const evens    = nums.filter(n => n % 2 === 0); // [2,4]
const total    = nums.reduce((sum, n) => sum + n, 0); // 15
const hasThree = nums.some(n => n === 3);      // true
const allPos   = nums.every(n => n > 0);       // true
nums.forEach(n => console.log(n));             // log each

// Spread operator:
const a = [1, 2, 3];
const b = [4, 5, 6];
const combined = [...a, ...b];   // [1,2,3,4,5,6]
const copy     = [...a];         // shallow copy

// Objects:
const person = {
    name: "Uzair",
    age: 25,
    greet() {
        return `Hi, I'm ${this.name}`;
    }
};
console.log(person.name);          // Uzair
console.log(person["age"]);        // 25
console.log(person.greet());       // Hi, I'm Uzair
person.email = "u@example.com";    // add property
delete person.age;                 // remove property
console.log("name" in person);     // true

// Destructuring:
const { name, email } = person;         // object destructuring
const [first, second] = fruits;         // array destructuring

// Spread for objects:
const updated = { ...person, age: 26 }; // copy + override

Chapter 6 โ€” Loops

// for loop:
for (let i = 0; i < 5; i++) {
    console.log(i);   // 0,1,2,3,4
}

// while loop:
let count = 0;
while (count < 3) {
    console.log(count);
    count++;
}

// for...of โ€” iterate array values:
const colors = ["red", "green", "blue"];
for (const color of colors) {
    console.log(color);
}

// for...in โ€” iterate object keys:
const car = { make: "Toyota", year: 2022 };
for (const key in car) {
    console.log(`${key}: ${car[key]}`);
}

// forEach โ€” array method:
colors.forEach((color, index) => {
    console.log(`${index}: ${color}`);
});

// break and continue work same as Python:
for (let i = 0; i < 10; i++) {
    if (i === 5) break;       // stop at 5
    if (i % 2 === 0) continue; // skip evens
    console.log(i);            // 1, 3
}

Chapter 7 โ€” The DOM

// DOM = Document Object Model
// JS can read and change HTML elements on the page

// Select elements:
const el  = document.getElementById("myId");           // by ID
const els = document.querySelectorAll(".myClass");      // all matches
const el2 = document.querySelector("h1");              // first match
const el3 = document.querySelector("div.card > p");    // CSS selector

// Read & change content:
el.textContent = "New text";        // set text (safe)
el.innerHTML   = "<b>Bold</b>";    // set HTML (be careful with XSS!)
console.log(el.textContent);       // read text

// Change styles:
el.style.color           = "red";
el.style.fontSize        = "24px";
el.style.backgroundColor = "#1a1a1a";
el.style.display         = "none";    // hide element
el.style.display         = "block";   // show element

// Change classes:
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");         // add if missing, remove if present
el.classList.contains("active");     // true/false

// Get & set attributes:
el.setAttribute("href", "https://kalirange.com");
const href = el.getAttribute("href");
el.removeAttribute("disabled");

// Create & add elements:
const p = document.createElement("p");
p.textContent = "New paragraph";
document.body.appendChild(p);        // add to end of body
el.prepend(p);                        // add as first child
el.remove();                          // remove from DOM

Chapter 8 โ€” Events

// Events let you respond to user actions
const btn = document.querySelector("#myButton");

// Add event listener:
btn.addEventListener("click", function() {
    console.log("Button clicked!");
});

// Arrow function (cleaner):
btn.addEventListener("click", () => {
    alert("Hello!");
});

// Common events:
click          โ†’ mouse click
dblclick       โ†’ double click
mouseover      โ†’ mouse enters element
mouseout       โ†’ mouse leaves element
keydown        โ†’ key pressed
keyup          โ†’ key released
input          โ†’ text field changes
change         โ†’ dropdown/checkbox changes
submit         โ†’ form submitted
load           โ†’ page fully loaded
DOMContentLoaded โ†’ HTML loaded (before images)

// Event object (info about the event):
btn.addEventListener("click", (event) => {
    console.log(event.target);        // element that was clicked
    console.log(event.type);          // "click"
    event.preventDefault();           // stop default (e.g. form submit)
});

// Keyboard events:
document.addEventListener("keydown", (e) => {
    console.log(e.key);   // "Enter", "a", "ArrowLeft", etc.
    if (e.key === "Enter") doSomething();
});

// Form submit:
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
    e.preventDefault();    // stop page reload
    const name = document.querySelector("#name").value;
    console.log("Submitted:", name);
});

Chapter 9 โ€” ES6+ Features

// Template literals (backticks):
const name = "Uzair";
console.log(`Hello, ${name}! You are ${25 + 1} years old.`);

// Destructuring:
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// a=1, b=2, rest=[3,4,5]

const { name: n, age = 25 } = { name: "Alice" };
// n="Alice", age=25 (default)

// Optional chaining โ€” no crash if null:
const user = null;
console.log(user?.name);           // undefined (no error)
console.log(user?.address?.city);  // undefined (no error)

// Nullish coalescing โ€” default if null/undefined:
const x = null ?? "default";       // "default"
const y = 0 ?? "default";          // 0 (0 is not null!)
const z = 0 || "default";          // "default" (|| treats 0 as falsy)

// Modules (ES6):
// utils.js:
export const PI = 3.14;
export function double(x) { return x * 2; }

// main.js:
import { PI, double } from './utils.js';
import * as utils from './utils.js';

// Classes:
class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        return `${this.name} makes a sound.`;
    }
}
class Dog extends Animal {
    speak() {
        return `${this.name} barks!`;
    }
}
const d = new Dog("Rex");
console.log(d.speak());   // Rex barks!

Chapter 10 โ€” Fetch API & JSON

// JSON = JavaScript Object Notation โ€” how data is sent between servers and browsers
const obj = { name: "Alice", age: 25 };
const json = JSON.stringify(obj);   // '{"name":"Alice","age":25}'
const back = JSON.parse(json);       // { name: "Alice", age: 25 }

// Fetch API โ€” get data from a URL:
fetch("https://api.example.com/users")
    .then(response => response.json())   // parse JSON body
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error("Error:", error);
    });

// POST request (send data):
fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({ name: "Uzair", email: "u@example.com" })
})
    .then(res => res.json())
    .then(data => console.log(data));

Chapter 11 โ€” Async / Await

// async/await = cleaner way to handle async operations

async function getUser() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
        const user = await response.json();
        console.log(user.name);
    } catch (error) {
        console.error("Failed:", error);
    }
}
getUser();

// Fetch multiple URLs in parallel:
async function getMultiple() {
    const [users, posts] = await Promise.all([
        fetch("/api/users").then(r => r.json()),
        fetch("/api/posts").then(r => r.json())
    ]);
    console.log(users, posts);
}

// Understanding Promises:
const promise = new Promise((resolve, reject) => {
    const success = true;
    if (success) resolve("Done!");
    else         reject("Failed!");
});

promise
    .then(result => console.log(result))  // Done!
    .catch(err   => console.error(err));

Chapter 12 โ€” Projects

// PROJECT 1: Dynamic To-Do List

<!-- HTML -->
<input id="taskInput" placeholder="Add a task..."/>
<button id="addBtn">Add</button>
<ul id="taskList"></ul>

// JS:
const input    = document.getElementById("taskInput");
const addBtn   = document.getElementById("addBtn");
const taskList = document.getElementById("taskList");

addBtn.addEventListener("click", () => {
    const text = input.value.trim();
    if (!text) return;

    const li = document.createElement("li");
    li.innerHTML = `
        ${text}
        <button onclick="this.parentElement.remove()">โœ•</button>
    `;
    taskList.appendChild(li);
    input.value = "";
});

input.addEventListener("keydown", e => {
    if (e.key === "Enter") addBtn.click();
});

// PROJECT 2: Fetch & Display Users
async function loadUsers() {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    const users = await res.json();
    const container = document.getElementById("users");
    container.innerHTML = users.map(u =>
        `<div class="card">
            <h3>${u.name}</h3>
            <p>${u.email}</p>
        </div>`
    ).join("");
}
loadUsers();
โœ…
Workbook Complete! JavaScript is the language of the web. Build small projects, explore browser DevTools, and try frameworks like React or Vue once you're comfortable with the basics.
JavaScript Coding Lab โ†’ โ† All Workbooks
๐Ÿ“–
Sign in to track progress