JavaScript Cheat Sheet
JavaScript is a dynamic, prototype-based programming language used for web, server-side, and cross-platform development. This JavaScript cheatsheet is an example-driven reference covering core syntax, functions, objects, asynchronous programming, and commonly used APIs.
Running JavaScript
node app.js
<script src="app.js"></script>
<script type="module" src="app.mjs"></script>
Variables
var a = 1;
let b = 2;
const c = 3;
Data Types
number
string
boolean
null
undefined
symbol
bigint
object
typeof 10;
typeof "text";
Strings
const s = "JavaScript";
s.length;
s.toUpperCase();
s.includes("Script");
const name = "World";
`Hello ${name}`;
Numbers
Number.isInteger(10);
Math.round(3.6);
Math.max(1, 5, 3);
Operators
a + b;
a - b;
a * b;
a / b;
a % b;
a === b;
a !== b;
a > b;
a < b;
a && b;
a || b;
!a;
Control Flow
if / else
if (x > 10) {
result = 1;
} else {
result = 0;
}
switch
switch (x) {
case 1:
break;
default:
break;
}
Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}
while (x > 0) {
x--;
}
for (const item of list) {
console.log(item);
}
for (const key in obj) {
console.log(key);
}
Functions
function add(a, b) {
return a + b;
}
const sum = add(2, 3);
Arrow Functions
const square = (x) => x * x;
const inc = x => x + 1;
Default Parameters
function multiply(a, b = 2) {
return a * b;
}
Rest Parameters
function total(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
Arrays
const arr = [1, 2, 3];
arr.push(4);
arr.pop();
arr.length;
Array Methods
arr.map(n => n * 2);
arr.filter(n => n > 1);
arr.find(n => n === 2);
arr.includes(3);
Objects
const user = {
name: "A",
age: 20,
};
user.name;
user["age"];
Destructuring
const { name, age } = user;
const [a, b] = arr;
Spread Operator
const copy = [...arr];
const merged = { ...obj1, ...obj2 };
Optional Chaining
user.address?.city;
Nullish Coalescing
const v = value ?? "default";
Classes
class Counter {
constructor() {
this.value = 0;
}
increment() {
this.value++;
}
}
const c = new Counter();
c.increment();
Prototypes
function Box(v) {
this.value = v;
}
Box.prototype.get = function () {
return this.value;
};
Modules
export function add(a, b) {
return a + b;
}
import { add } from "./math.js";
JSON
const json = JSON.stringify({ a: 1 });
const obj = JSON.parse(json);
Dates
const now = new Date();
now.toISOString();
Promises
const p = new Promise((resolve, reject) => {
resolve(42);
});
p.then(v => console.log(v));
Async / Await
async function fetchValue() {
return 42;
}
const v = await fetchValue();
Error Handling
try {
throw new Error("fail");
} catch (e) {
console.error(e.message);
}
Timers
setTimeout(() => console.log("later"), 1000);
setInterval(() => console.log("tick"), 1000);
DOM Selection
document.querySelector("#id");
document.querySelectorAll(".class");
DOM Events
button.addEventListener("click", () => {
console.log("clicked");
});
Fetch API
fetch("/api/data")
.then(r => r.json())
.then(d => console.log(d));
const res = await fetch("/api/data");
const data = await res.json();