Array methods
map, filter and the object shorthand — the operations most day-to-day JavaScript is made of.
const users = [
{ name: "Vivek", role: "admin" },
{ name: "Rahul", role: "editor" },
{ name: "Amit", role: "viewer" },
];
const names = users.map((user) => user.name);
console.log(names);
const admins = users.filter((user) => user.role === "admin");
console.log("Admins:", admins);
async / await
Top-level await, Promise.all for parallel work, and console.time to measure the difference against a sequential loop.
// Top-level await works here — no wrapper function needed.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fetchUser(id) {
await wait(150);
return { id, name: "User " + id };
}
console.log("Fetching three users in parallel...");
const users = await Promise.all([1, 2, 3].map(fetchUser));
console.table(users);
console.time("sequential");
for (const id of [4, 5]) {
const user = await fetchUser(id);
console.log("Got", user.name);
}
console.timeEnd("sequential");
Classes & inheritance
Class inheritance with super, private #fields, a getter, and sorting objects by a computed value.
class Shape {
constructor(name) {
this.name = name;
}
area() {
return 0;
}
toString() {
return this.name + " with area " + this.area().toFixed(2);
}
}
class Circle extends Shape {
#radius;
constructor(radius) {
super("Circle");
this.#radius = radius;
}
area() {
return Math.PI * this.#radius ** 2;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super("Rectangle");
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const shapes = [new Circle(3), new Rectangle(4, 5)];
for (const shape of shapes) {
console.log(String(shape));
}
shapes.sort((a, b) => b.area() - a.area());
console.log("Largest:", shapes[0].name);
Reading input (stdin)
Reading standard input with readline() and prompt() — the pattern coding-judge problems use.
// Values come from the Input panel — one per line.
const name = readline();
const age = Number(readline());
console.log("Hello, " + name + "!");
if (Number.isNaN(age)) {
console.error("That age wasn't a number.");
} else {
console.log("Next year you turn " + (age + 1) + ".");
}
const city = prompt("Which city?");
console.log("City:", city ?? "(nothing left to read)");
Closures & memoisation
A counter that keeps private state, and memoisation with a Map, which is why fib(90) returns instantly.
function counter(start = 0) {
let count = start;
return {
increment: () => ++count,
decrement: () => --count,
get value() {
return count;
},
};
}
const clicks = counter();
clicks.increment();
clicks.increment();
clicks.decrement();
console.log("Clicks:", clicks.value);
function memoize(fn) {
const cache = new Map();
return (n) => {
if (cache.has(n)) return cache.get(n);
const result = fn(n);
cache.set(n, result);
return result;
};
}
const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
console.log("fib(90) =", fib(90));
Map, Set & console.table
Grouping with Map, de-duplicating with Set, and printing a real table with console.table.
const orders = [
{ id: "A-1", city: "Jaipur", total: 2400 },
{ id: "A-2", city: "Pune", total: 990 },
{ id: "A-3", city: "Jaipur", total: 1500 },
];
console.table(orders);
const byCity = new Map();
for (const order of orders) {
byCity.set(order.city, (byCity.get(order.city) ?? 0) + order.total);
}
console.log(byCity);
console.log("Unique cities:", new Set(orders.map((order) => order.city)));
const sorted = [...byCity.entries()].sort((a, b) => b[1] - a[1]);
console.log("Top city:", sorted[0][0], "->", sorted[0][1]);
Errors & debugging
throw and catch with a custom error type, plus what an uncaught exception reports.
function parseAge(input) {
const age = Number(input);
if (Number.isNaN(age)) {
throw new TypeError(input + " is not a number");
}
return age;
}
for (const value of ["31", "abc"]) {
try {
console.log("Parsed:", parseAge(value));
} catch (error) {
console.error("Failed on", value, "->", error.message);
}
}
console.warn("This is a warning.");
console.log({ nested: { deep: { value: [1, 2, { ok: true }] } } });
// An uncaught throw reports its line — click the line number to jump there.
null.forEach(() => {});