Practice library / Web applications and APIs
Workbook · Easy · 5 hours
JavaScript Basics
ES6+, DOM, async/await, and security implications of JavaScript.
On this page 12 sections
- ·Chapter 1 — What is JavaScript?
- ·Chapter 2 — Variables & Types
- ·Chapter 3 — Operators & Conditionals
- ·Chapter 4 — Functions
- ·Chapter 5 — Arrays & Objects
- ·Chapter 6 — Loops
- ·Chapter 7 — The DOM
- ·Chapter 8 — Events
- ·Chapter 9 — ES6+ Features
- ·Chapter 10 — Fetch API & JSON
- ·Chapter 11 — Async / Await
- ·Chapter 12 — Projects
Before you start
JavaScript runs inside every major browser and on many servers. It changes the DOM, calls APIs, and appears in many web attacks and web defences. A security engineer who reads JavaScript well can trace a phishing kit, review a cross-site scripting fix, and deobfuscate a malicious payload. This workbook starts from zero: variables, functions, arrays, objects, the DOM, events, fetch, and promises. Each chapter uses short examples that run in the browser console or a plain HTML file. The paired lab and the deobfuscation lab let the reader apply these pieces to real pages and real malicious scripts.
No installation needed. Open any browser, right-click the page, select Inspect, and open the Console tab. Type JavaScript directly and press Enter. Alternatively, create an HTML file, add <script> tags, and open the file in a browser.
Chapter 1 — What is JavaScript?
HTML gives a page its structure, CSS gives it its style, and JavaScript gives it behaviour: it makes pages respond to the user. JavaScript 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/falseChapter 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 + overrideChapter 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 main programming language of the browser. Build small projects, explore browser DevTools, and try frameworks such as React or Vue once the basics are familiar.
Sign in to track progress and send feedback.
Related
This workbook is extra practice for the course Web applications and APIs. Do the lessons first.Open the course