Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.
They work on both sides of an application: the front end (what users see and click) and the back end (servers, databases, APIs). They also handle the glue, such as deployment, security and testing. You don't have to be an expert in everything, but you should be able to follow a feature from the button click to the database row and back.
The browser looks up the domain's IP address through DNS, opens a TCP connection (with TLS for HTTPS), and sends an HTTP request. The server processes it, perhaps querying a database, and sends back a response. The browser then parses the HTML, fetches CSS, JS and images, and paints the page.
HTTPS is HTTP wrapped in TLS encryption. It keeps data private in transit, prevents tampering, and verifies the server's identity through a certificate. Today it's the default for every site, and browsers warn users when it's missing.
GET reads, POST creates, PUT replaces a whole resource, PATCH changes part of one, and DELETE removes it. GET, PUT and DELETE are meant to be idempotent, so repeating them has the same effect as doing them once. POST is not.
REST exposes many URLs, each returning a fixed shape of data. GraphQL exposes one endpoint where the client asks for exactly the fields it needs. GraphQL avoids over-fetching and under-fetching, but it adds complexity in caching and query cost control. REST is simpler and works well for most apps.
Every element is a box made of content, padding, border and margin, from the inside out. With box-sizing: border-box, the width you set includes padding and border, which makes layout math far easier.
Flexbox lays things out along one axis, a row or a column, so it suits navbars and centering. Grid handles two dimensions at once, rows and columns together, so it suits page layouts and card galleries. They're often combined.
Tags like <header>, <nav>, <main> and <button> tell browsers, screen readers and search engines what each part means. It improves accessibility and SEO, and it gives you built-in behavior, such as keyboard support on a real button, for free.
A closure is a function that remembers the variables from the place where it was created, even after that outer function has finished. They're how you get private state, like a counter that outside code can't touch directly.
var is function-scoped and hoisted with an undefined value, which causes surprises. let and const are block-scoped and sit in a "temporal dead zone" until declared. const prevents reassignment, but an object or array held in it can still be modified.
== converts types before comparing, so "5" == 5 is true. === compares without conversion, so it's false. Using === avoids odd coercion bugs.
When you click an element, the event fires on it and then travels up through its ancestors. Delegation takes advantage of this by attaching one listener to a parent and checking event.target. It uses less memory and also works for elements added later.
JavaScript runs on one thread. Slow work like network calls is handed to the browser or runtime, and the callback returns through the event loop. Microtasks (promise handlers) run before macrotasks (timers), so Promise.then runs before a setTimeout(..., 0).
Cookies are sent automatically with each request to the server and can be marked HttpOnly, so scripts can't read them. localStorage persists until cleared, is readable by any script on the page, and is never sent automatically. sessionStorage is the same but disappears when the tab closes. Sensitive tokens are safer in HttpOnly cookies.
Authentication asks who you are, such as logging in. Authorization asks what you're allowed to do, such as whether you can delete this post. You need both, and the second is checked on every protected request.
With sessions, the server stores login state and gives the browser a session ID cookie. With tokens such as JWTs, the server signs a self-contained token and stores nothing. Sessions are easy to revoke, while tokens scale nicely across servers but are harder to invalidate early.
XSS is when an attacker gets a script to run on your page, defended by escaping output and using a Content Security Policy. CSRF tricks a logged-in user's browser into sending an unwanted request, defended by SameSite cookies and CSRF tokens. SQL injection slips SQL through user input, defended by parameterized queries.
A browser rule that stops a page from one origin reading responses from another origin unless the server opts in with headers such as Access-Control-Allow-Origin. It's enforced by the browser, not the server, and it doesn't stop tools like curl.
SQL databases use tables with fixed schemas and are strong at relationships, joins and transactions. NoSQL databases (document, key-value, graph) trade some of that for flexible schemas and easy horizontal scaling. Pick based on your data shape and query needs, not on fashion.
Atomicity (all steps happen or none do), Consistency (rules stay valid), Isolation (concurrent transactions don't interfere), and Durability (committed data survives a crash). A bank transfer is the classic example.
Normalization splits data into related tables to avoid duplicated information and update errors. An index is an extra structure, usually a B-tree, that lets the database find rows without scanning the whole table. Indexes speed up reads but cost storage and slow writes slightly.
You load a list with one query, then run one more query per item to fetch related data, so 100 posts cause 101 queries. Fix it with a join, eager loading or batching.
A monolith is one deployable app: simple to build, test and run. Microservices split it into small independent services that scale and deploy separately, at the cost of network calls, distributed debugging and operational overhead. Most teams should start with a well-organized monolith.
Caching stores results of expensive work so it isn't repeated, in the browser, in memory (like Redis), or at the edge. A CDN copies static files to servers around the world so users download from a nearby location. Both cut latency and load, and the hard part is invalidating stale data.
Docker packages an app with its dependencies into a container that runs the same everywhere. CI/CD is an automated pipeline: every push runs tests and builds (continuous integration), and passing builds can be deployed automatically (continuous delivery). Together they turn "it works on my machine" into a repeatable process.
The labels are linked to their inputs, so screen readers and click-to-focus work, and the browser validates basics with no JavaScript.
<form action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="pw">Password</label>
<input id="pw" name="password" type="password" minlength="8" required>
<button type="submit">Create account</button>
</form>
Use CSS grid place-items: center for page centering and auto-fit repeat for responsive columns.
* { box-sizing: border-box; }
.page {
min-height: 100vh;
display: grid;
place-items: center;
}
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1rem;
}
Clear and set a timer on every invocation using setTimeout closure.
function debounce(fn, wait = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const onType = debounce((text) => console.log("search:", text), 400);
Attach single click listener to parent element and use e.target.closest("li").
document.querySelector("#todos").addEventListener("click", (e) => {
const item = e.target.closest("li");
if (!item) return;
item.classList.toggle("done");
});
Fetch only rejects on network failures, so explicitly check res.ok before parsing res.json().
async function getJSON(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
try {
const users = await getJSON("/api/users");
console.log(users);
} catch (err) {
console.error(err.message);
}
Use Promise.all to fail fast if any promise rejects, or Promise.allSettled to collect all outcomes.
const [user, posts] = await Promise.all([
getJSON("/api/user"), getJSON("/api/posts"),
]);
const results = await Promise.allSettled([
getJSON("/api/a"), getJSON("/api/b"),
]);
const good = results.filter(r => r.status === "fulfilled").map(r => r.value);
Encapsulate private counter variable inside outer function returning method object.
function makeCounter(start = 0) {
let count = start;
return {
up: () => ++count,
down: () => --count,
value: () => count,
};
}
const c = makeCounter(5);
c.up(); c.up();
console.log(c.value()); // 7
Validate req.body properties before adding to data store and returning 201 Created payload.
const express = require("express");
const app = express();
app.use(express.json());
const books = [];
app.post("/api/books", (req, res) => {
const { title, pages } = req.body;
if (typeof title !== "string" || !title.trim()) {
return res.status(400).json({ error: "title is required" });
}
if (!Number.isInteger(pages) || pages <= 0) {
return res.status(400).json({ error: "pages must be a positive integer" });
}
const book = { id: books.length + 1, title: title.trim(), pages };
books.push(book);
res.status(201).json(book);
});
Define REFERENCES for foreign key constraint with ON DELETE CASCADE and create explicit index.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(80) NOT NULL,
email VARCHAR(120) UNIQUE NOT NULL
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
amount NUMERIC(10,2) NOT NULL CHECK (amount > 0),
created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_orders_user ON orders(user_id);
Join users and orders tables, group by user ID, and filter aggregate totals using HAVING.
SELECT u.name, COUNT(o.id) AS orders, SUM(o.amount) AS total
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 0
ORDER BY total DESC;
Filter for maximum salary less than overall maximum or sort distinct salaries with OFFSET 1.
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Alternative query:
-- SELECT DISTINCT salary FROM employees ORDER BY salary DESC OFFSET 1 LIMIT 1;
Pass values separately in parameter array instead of concatenating raw strings into SQL.
// GOOD: the value travels separately from the SQL statement
const { rows } = await pool.query(
"SELECT id, name FROM users WHERE email = $1",
[email]
);
Track IP request timestamps inside a Map structure and return 429 status on threshold breach.
function rateLimit({ windowMs = 60_000, max = 30 } = {}) {
const hits = new Map();
return (req, res, next) => {
const now = Date.now();
const rec = hits.get(req.ip) || { count: 0, start: now };
if (now - rec.start > windowMs) { rec.count = 0; rec.start = now; }
rec.count++;
hits.set(req.ip, rec);
if (rec.count > max) return res.status(429).json({ error: "Too many requests" });
next();
};
}
app.use("/api", rateLimit({ max: 100 }));
Set httpOnly, secure, and sameSite options on response cookie header.
res.cookie("session", token, {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: 1000 * 60 * 60 * 24,
});
Use AbortController signal inside useEffect to cancel pending network requests on unmount.
import { useState, useEffect } from "react";
export function useFetch(url) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
const controller = new AbortController();
setState({ data: null, loading: true, error: null });
fetch(url, { signal: controller.signal })
.then(r => { if (!r.ok) throw new Error(r.status); return r.json(); })
.then(data => setState({ data, loading: false, error: null }))
.catch(err => {
if (err.name !== "AbortError") setState({ data: null, loading: false, error: err.message });
});
return () => controller.abort();
}, [url]);
return state;
}
Calculate OFFSET as (page - 1) * limit and cap requested page size.
app.get("/api/orders", async (req, res) => {
const page = Math.max(parseInt(req.query.page) || 1, 1);
const limit = Math.min(parseInt(req.query.limit) || 10, 50);
const { rows } = await pool.query(
"SELECT * FROM orders ORDER BY id DESC LIMIT $1 OFFSET $2",
[limit, (page - 1) * limit]
);
res.json({ page, limit, rows });
});
Leverage JavaScript Map key insertion ordering to evict least recently used entries.
class LRUCache {
constructor(capacity) {
this.cap = capacity;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return undefined;
const val = this.map.get(key);
this.map.delete(key);
this.map.set(key, val);
return val;
}
set(key, val) {
this.map.delete(key);
this.map.set(key, val);
if (this.map.size > this.cap) {
this.map.delete(this.map.keys().next().value);
}
}
}
Copy package files first to cache dependency installation step.
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 5000
CMD ["node", "server.js"]
Define service dependencies, environment variables, ports, and volume mounts.
services:
api:
build: .
ports: ["5000:5000"]
environment:
DATABASE_URL: postgres://app:secret@db:5432/appdb
depends_on: [db]
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
volumes: [pgdata:/var/lib/postgresql/data]
volumes:
pgdata:
Use branch creation, commits, rebase onto main, and pull request push commands.
git switch -c feature/login # new branch
git add .
git commit -m "Add login form validation"
git fetch origin
git rebase origin/main # replay your work on top of latest main
git push -u origin feature/login # then open a pull request
# Undo helpers:
git restore file.js # discard local edits
git revert <commit> # safe undo on shared branches
git stash / git stash pop # park unfinished work
Write test assertions checking expected outputs against sample inputs.
// sum.js
exports.total = (items) => items.reduce((s, i) => s + i.price * i.qty, 0);
// sum.test.js
const { total } = require("./sum");
test("adds up price times quantity", () => {
expect(total([{ price: 10, qty: 2 }, { price: 5, qty: 1 }])).toBe(25);
});
test("returns 0 for an empty cart", () => {
expect(total([])).toBe(0);
});
Assert status codes and response JSON payloads on Express app instance.
const request = require("supertest");
const app = require("./app");
test("rejects a book with no title", async () => {
const res = await request(app).post("/api/books").send({ pages: 100 });
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/title/);
});
test("creates a valid book", async () => {
const res = await request(app).post("/api/books").send({ title: "Dune", pages: 612 });
expect(res.status).toBe(201);
expect(res.body).toMatchObject({ title: "Dune" });
});
Use cors() middleware with explicit whitelist origin array and credentials: true.
const cors = require("cors");
app.use(cors({
origin: ["https://myapp.com", "http://localhost:5173"],
methods: ["GET", "POST", "PATCH", "DELETE"],
credentials: true,
}));
Define workflow triggers and test job steps in .github/workflows/ci.yml.
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
Broadcast incoming WebSocket messages to all connected client sockets.
// server.js (npm i ws)
const { WebSocketServer, WebSocket } = require("ws");
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (socket) => {
socket.on("message", (data) => {
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN) client.send(data.toString());
}
});
});
// browser
const ws = new WebSocket("ws://localhost:8080");
ws.onmessage = (e) => console.log("Received:", e.data);
ws.onopen = () => ws.send("Hello everyone");
Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".
Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.