A comprehensive cheat sheet for the Frontend Machine Coding Interview Round, which helps to revise all the important machine coding & UI design concepts before the interview.
Anuj Sharma
Last Updated Jun 13, 2025
Advertisement
Machine coding interviews are a must in all tech companies hiring for frontend/UI roles at any level. There are plenty of machine coding questions out there that can become part of the frontend interview, but the underlying concepts are quite common.
As part of this Frontend Machine Coding Cheat-Sheet, we aim to capture common concepts in a single blog post, so that anyone can revise all the important concepts from a single place.
Let's jump to the topic
Here are the important concepts to revise before every machine coding interview.
Array.includes()
or a Regex expression
// π Using Includes
const data = [
{ name: "Alice Johnson", role: "Developer" },
{ name: "Bob Smith", role: "Designer" },
{ name: "Charlie Brown", role: "Project Manager" },
];
const searchTerm = "Bob";
const resultIncludes = data.filter(item =>
item.name.includes(searchTerm) || item.role.includes(searchTerm)
);
console.log("Search using includes():", resultIncludes);
// π Using Regex
const regex = new RegExp(searchTerm, "i"); // 'i' for case-insensitive
const resultRegex = data.filter(item =>
regex.test(item.name) || regex.test(item.role)
);
console.log("Search using RegExp:", resultRegex);
1οΈβ£ Search Box with Auto-suggestion
<label for="search">Search:</label>
<input
type="text"
id="search"
role="combobox"
aria-autocomplete="list"
aria-expanded="false"
aria-controls="suggestions"
autocomplete="off"
/>
<ul id="suggestions" role="listbox" hidden></ul>
Keyboard support in the suggestion selection
const input = document.getElementById("search");
const list = document.getElementById("suggestions");
const suggestions = ["Apple", "Banana", "Blueberry", "Cherry", "Mango"];
let activeIndex = -1;
input.addEventListener("input", () => {
const value = input.value.toLowerCase();
const matched = suggestions.filter(s => s.toLowerCase().includes(value));
list.innerHTML = "";
activeIndex = -1;
if (matched.length > 0 && value) {
list.hidden = false;
input.setAttribute("aria-expanded", "true");
matched.forEach((item, index) => {
const li = document.createElement("li");
li.id = `suggestion-${index}`;
li.setAttribute("role", "option");
li.textContent = item;
li.addEventListener("click", () => {
input.value = item;
list.hidden = true;
input.setAttribute("aria-expanded", "false");
});
list.appendChild(li);
});
} else {
list.hidden = true;
input.setAttribute("aria-expanded", "false");
}
});
// Keyboard support
input.addEventListener("keydown", (e) => {
const items = list.querySelectorAll("li");
if (e.key === "ArrowDown") {
activeIndex = (activeIndex + 1) % items.length;
} else if (e.key === "ArrowUp") {
activeIndex = (activeIndex - 1 + items.length) % items.length;
} else if (e.key === "Enter" && activeIndex >= 0) {
input.value = items[activeIndex].textContent;
list.hidden = true;
input.setAttribute("aria-expanded", "false");
}
items.forEach((item, index) => {
item.classList.toggle("active", index === activeIndex);
});
});
2οΈβ£ A general search box without Auto-suggestion
<input
type="search" // Use semantic type in general search without suggestion
role="combobox"
aria-autocomplete="list"
aria-expanded="false"
aria-controls="suggestions"
aria-activedescendant=""
autocomplete="off"
/>
/* HTML */
<h2>Flexbox Listing</h2>
<div class="flex-container" id="flexList"></div>
/* CSS */
body {
font-family: sans-serif;
padding: 2rem;
background-color: #f9f9f9;
}
.flex-container {
display: flex;
flex-wrap: wrap;
gap: 1rem;
justify-content: center;
}
.flex-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
padding: 1rem;
width: 200px;
text-align: center;
}
/* JS */
const items = [
"HTML",
"CSS",
"JavaScript",
"React",
"Vue",
"Angular",
"Svelte"
];
const flexList = document.getElementById("flexList");
items.forEach((name) => {
const card = document.createElement("div");
card.className = "flex-card";
card.innerHTML = `<h4>${name}</h4>`;
flexList.appendChild(card);
});
<h1>ποΈ Product Catalog</h1>
<div class="catalog" id="catalog"></div>
h1 {
text-align: center;
margin-bottom: 2rem;
}
.catalog {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 1.5rem;
}
.product-card {
background: #fff;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
transition: transform 0.2s ease;
}
.product-card img {
width: 100%;
height: 160px;
object-fit: cover;
}
.product-info {
padding: 1rem;
}
.product-info h3 {
font-size: 1.1rem;
margin: 0 0 0.5rem;
}
.product-info p {
margin: 0;
color: #888;
}
.product-info .price {
font-weight: bold;
color: #333;
margin-top: 0.5rem;
}
const products = [
{
name: "Classic Sneakers",
price: "$59.99",
image: "https://images.unsplash.com/photo-1618354691373-5f1c94ef18d4?auto=format&fit=crop&w=400&q=80"
},
{
name: "Leather Backpack",
price: "$89.00",
image: "https://images.unsplash.com/photo-1600180758890-5b568f0a5a63?auto=format&fit=crop&w=400&q=80"
},
{
name: "Smart Watch",
price: "$199.99",
image: "https://images.unsplash.com/photo-1519838264761-1aa9af7fa66f?auto=format&fit=crop&w=400&q=80"
},
{
name: "Sunglasses",
price: "$39.99",
image: "https://images.unsplash.com/photo-1606811844664-c1b33e5c05c3?auto=format&fit=crop&w=400&q=80"
}
];
const catalog = document.getElementById("catalog");
products.forEach(product => {
const card = document.createElement("div");
card.className = "product-card";
card.innerHTML = `
<img src="${product.image}" alt="${product.name}">
<div class="product-info">
<h3>${product.name}</h3>
<p class="price">${product.price}</p>
</div>
`;
catalog.appendChild(card);
});
Intersection observer
How it works in summary
IntersectionObserver
watches this element.// JavaScript
const container = document.getElementById("item-container");
const loader = document.getElementById("loader");
let itemCount = 0;
const batchSize = 10;
function loadItems(count) {
for (let i = 0; i < count; i++) {
const item = document.createElement("div");
item.className = "item";
item.textContent = `Product ${++itemCount}`;
container.appendChild(item);
}
}
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
if (entry.isIntersecting) {
// Simulate loading delay
setTimeout(() => {
loadItems(batchSize);
}, 500);
}
});
// Initial load
loadItems(batchSize);
observer.observe(loader);
<h2>π Infinite Scroll Example</h2>
<div id="item-container"></div>
<div class="loader" id="loader">Loading more items...</div>
.item {
background: #fff;
margin-bottom: 1rem;
padding: 1rem;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
border-radius: 6px;
}
.loader {
text-align: center;
padding: 1rem;
font-size: 1rem;
color: #777;
}
Most of the companies, asks machine coding questions which involvs dynamic fetching of data using the API calls. In interviews using the third party libraries like axios are not recommended, so its important to know how the built-in fetch() call works for GET and POST API calls. PATCH/PUT works similar to POST.
π GET API call example using fetch()
/* HTML */
<h2>π° Posts</h2>
<div id="posts-container">
Loading posts...
</div>
/* JavaScript */
const container = document.getElementById("posts-container");
async function fetchPosts() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts?_limit=5"
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const posts = await response.json();
container.innerHTML = ""; // Clear loading text
posts.forEach((post) => {
const div = document.createElement("div");
div.className = "post";
div.innerHTML = `
<h3>${post.title}</h3>
<p>${post.body}</p>
`;
container.appendChild(div);
});
} catch (error) {
container.innerHTML = `<p style="color:red;">β Error: ${error.message}</p>`;
}
}
fetchPosts();
π POST API call example
/* HTML */
<h2>Create a New Post</h2>
<form id="postForm">
<input type="text" id="title" placeholder="Title" required />
<textarea id="body" placeholder="Body" required></textarea>
<button type="submit">Submit Post</button>
</form>
<div id="result" class="response" style="display:none;"></div>
/* JavaScript */
const form = document.getElementById("postForm");
const resultDiv = document.getElementById("result");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const title = document.getElementById("title").value;
const body = document.getElementById("body").value;
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title,
body,
userId: 1 // optional
})
});
const data = await response.json();
alert(
`β
Post submitted successfully! ${data.id} | ${data.title} | ${data.body}`
);
} catch (error) {
alert(`βAPI failed, Error: ${error.message}`);
}
});
π Cancel the fetch API call using AbortController
API call cancellation is a common requirement asked in machine coding interviews. In case of fetching dynamic data from APIs, there is a possibility of multiple api calls or api calls taking more time than expected or a navigation change. All of these situations required the cancellation of already running API calls automatically or manual intervention.
AbortController is a built-in class which provides a signal-based approach to pass signals to the fetch call to cancel the API calls. Here is the example ππ
/* HTML */
<h2>Cancel Fetch Request Example</h2>
<button id="startBtn">Start API Call</button>
<button id="cancelBtn">Cancel API Call</button>
<div class="log" id="log">Click "Start API Call" to begin.</div>
/* JavaScript */
let controller;
document.getElementById("startBtn").addEventListener("click", async () => {
const log = document.getElementById("log");
// Create an AbortController instance.
controller = new AbortController();
const signal = controller.signal;
log.textContent = "Fetching data...";
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
signal // Pass signal in API call
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
log.textContent = `Fetched ${data.length} posts`;
} catch (error) {
if (error.name === "AbortError") {
log.textContent = "Aborted by user.";
} else {
log.textContent = `Error: ${error.message}`;
}
}
});
document.getElementById("cancelBtn").addEventListener("click", () => {
if (controller) {
// Cancel call by sending Abort signal
controller.abort();
}
});
Parallel API calls are important for performance improvement in the case of multiple API calls to fetch dynamic data from the Server, There are primarily 2 ways to parallel API calls.
π Parallel API call using Promise.all()
Promise.all() should be used to call the parallel apis when success of all the APIs are necessary for the application, and failure of any one of the API leads to the failure of all the other APIs as well.
/* HTML */
<h2>Parallel API Calls with using Promise.all()</h2>
<button id="callBtn">Call API in Parallel</button>
/* JavaScript */
async function fetchData() {
try {
const [posts, users] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/posts").then((res) =>
res.json()
),
fetch("https://jsonplaceholder.typicode.com/users").then((res) =>
res.json()
)
]);
alert(
`β
Posts fetched: ${posts.length}\nβ
Users fetched: ${users.length}`
);
} catch (error) {
alert(`β Error: ${error.message}`);
}
}
const callBtn = document.getElementById("callBtn");
document.addEventListener("click", () => {
fetchData();
});
π Parallel API call using Promise.allSettled()
Promise.allSettled() provides a more robust way to handle parallel api calls by providing the status of fulfilled or rejected for all the API call responses so that we can handle the respective cases explicitly in the application.
/* HTML */
<h2>π¦ Parallel API Calls with Promise.allSettled()</h2>
<div id="output">Loading...</div>
/* JavaScript */
async function fetchData() {
const results = await Promise.allSettled([
fetch("https://jsonplaceholder.typicode.com/posts").then((res) =>
res.json()
),
fetch("https://jsonplaceholder.typicode.com/users").then((res) =>
res.json()
),
fetch("https://jsonplaceholder.typicode.com/invalid-endpoint").then((res) =>
res.json()
)
]);
let output = "";
results.forEach((result, index) => {
if (result.status === "fulfilled") {
output += `β
Request ${index + 1} succeeded with ${
result.value.length
} items\n`;
} else {
output += `β Request ${index + 1} failed: ${result.reason}\n`;
}
});
document.getElementById("output").textContent = output;
}
fetchData();
In general cases, for event handling, it is advisable to use event listeners when there are few elements where listeners need to be added to the DOM elements.
In cases where there are so many DOM elements where attaching a event listeners to each and every DOM element are not efficient, In those cases, Event delegation does the job. You can attach an event to the parent of the DOM elements, and the parent captures the events when the event bubbles up from child elements to the parent.
π οΈ Use-cases
Here is an example of handling the most common events in JavaScript - click, dblclick, scroll, keydown, mousemove
/* HTML */
<button id="clickBtn">Click Me</button>
<button id="dblClickBtn">Double Click Me</button>
<div id="log">π Event log:</div>
const log = document.getElementById("log");
function appendLog(message) {
const timestamp = new Date().toLocaleTimeString();
log.innerHTML = `Log:: ${timestamp} - ${message}<br>` + log.innerHTML;
}
// Click
document.getElementById("clickBtn").addEventListener("click", () => {
appendLog("Button Clicked");
});
// Double Click
document.getElementById("dblClickBtn").addEventListener("dblclick", () => {
appendLog("Button Double Clicked");
});
// Scroll
window.addEventListener("scroll", () => {
appendLog(`Page Scrolled (Y: ${window.scrollY})`);
});
// Key Press
document.addEventListener("keydown", (e) => {
appendLog(`Key Pressed: "${e.key}"`);
});
// Mouse Move
document.addEventListener("mousemove", (e) => {
appendLog(`Mouse at X: ${e.clientX}, Y: ${e.clientY}`);
});
In cases where there is a requirement to add event listeners to many DOM elements, a normal event listener won't be efficient in this case. To implement event delegation, an event listener is applied to the parent element (which covers all the child elements), and whenever the user performs any event on the child, that event gets bubbled up to the parent and is captured there to perform.
Use-cases
/* HTML */
<h2>Event Delegation Example - Click a card</h2>
<div class="grid-container" id="grid">
<!-- 12 cards generated -->
<div class="card" data-id="1">Item 1</div>
<div class="card" data-id="2">Item 2</div>
<div class="card" data-id="3">Item 3</div>
<div class="card" data-id="4">Item 4</div>
<div class="card" data-id="5">Item 5</div>
<div class="card" data-id="6">Item 6</div>
<div class="card" data-id="7">Item 7</div>
<div class="card" data-id="8">Item 8</div>
<div class="card" data-id="9">Item 9</div>
<div class="card" data-id="10">Item 10</div>
<div class="card" data-id="11">Item 11</div>
<div class="card" data-id="12">Item 12</div>
</div>
/* CSS */
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 1rem;
}
.card {
background-color: #f0f0f0;
border: 1px solid #ccc;
padding: 1rem;
text-align: center;
cursor: pointer;
border-radius: 8px;
transition: transform 0.2s;
}
/* JS */
const grid = document.getElementById("grid");
// Event Delegation
grid.addEventListener("click", function (event) {
const card = event.target.closest(".card");
if (card) {
const id = card.dataset.id;
alert(`β
You clicked on Card ${id}`);
}
});
Debouncing allows a way to trigger a function after the user stops providing input for a delay. Debouncing can be used to increase the performance in use-cases like auto-search, type-ahead search, resizing window, etc. Learn More about Debouncing
π Live Code Example
/* HTML */
<h2>Debounced Search Input</h2>
<input type="text" id="searchInput" placeholder="Type to search..." />
<p id="result">Waiting ...</p>
/* JavaScript */
const result = document.getElementById("result");
function debounce(fn, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
function handleSearch(e) {
result.textContent = `π Search for: ${e.target.value}`;
}
const debouncedSearch = debounce(handleSearch, 500);
document
.getElementById("searchInput")
.addEventListener("input", debouncedSearch);
Throttling provides a way to ensure the function runs at most once every set interval, rather than calling every time on a frequently called event like scrolling. Throttling can be used to improve the performance in cases like events on webpage scrolling, events on mousemove, resize window, etc. Learn More about Throttling
π Live Code Example
/* HTML */
<div id="status">Scroll to see throttle in action</div>
/* JavaScript */
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}
function handleScroll() {
document.getElementById(
"status"
).textContent = `π Scroll Y: ${window.scrollY}`;
}
const throttledScroll = throttle(handleScroll, 300);
window.addEventListener("scroll", throttledScroll);
Responsiveness is one of the most common non-functional requirements for most applications and components. It's important to understand the Media Queries CSS to make responsive components which can be utilised for major display sizes like desktop, laptop/tablet, and mobile. Here is the example usageππ
/* HTML */
<div class="box">
Responsive Box<br>
Resize the browser to see color and text size change!
</div>
/* CSS */
.box {
padding: 2rem;
text-align: center;
color: white;
font-size: 1.5rem;
border-radius: 8px;
}
/* Desktop */
@media (min-width: 701px) {
.box {
background-color: red;
font-size: 1.2rem;
}
}
/* Tablet: 768px to 1023px */
@media (max-width: 700px) and (min-width: 501px) {
.box {
background-color: green;
font-size: 1.2rem;
}
}
/* Mobile: 767px and below */
@media (max-width: 500px) {
.box {
background-color: blue;
font-size: 1rem;
}
}
Understanding modal creation is important for machine coding interviews because the same modal creation logic can be used to create similar components. This type of question is best suited to test the overall understanding of HTML, CSS, and JavaScript, as it involves the Absolute positioning concept and JavaScript DOM manipulation concepts.
Here are the machine coding questions that utilise the same concepts
Modal Implementation Live Example
/* HTML */
<h2>Modal Example</h2>
<button id="openModalBtn">Open Modal</button>
<div id="modalOverlay" class="modal-overlay">
<div class="modal">
<button class="close-btn" id="closeModalBtn">×</button>
<h3>Hello</h3>
<p>This is a example modal dialog box.</p>
</div>
</div>
/* CSS */
/* Modal Styles */
.modal-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
justify-content: center;
align-items: center;
}
.modal {
background: white;
padding: 2rem;
border-radius: 8px;
max-width: 400px;
width: 90%;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
position: relative;
}
.close-btn {
position: absolute;
top: 0.5rem;
right: 0.75rem;
background: transparent;
border: none;
font-size: 1.25rem;
cursor: pointer;
}
.modal-overlay.show {
display: flex;
}
/* JS */
const openBtn = document.getElementById("openModalBtn");
const closeBtn = document.getElementById("closeModalBtn");
const overlay = document.getElementById("modalOverlay");
openBtn.addEventListener("click", () => {
overlay.classList.add("show");
});
closeBtn.addEventListener("click", () => {
overlay.classList.remove("show");
});
// Close when clicking outside the modal
overlay.addEventListener("click", (e) => {
if (e.target === overlay) {
overlay.classList.remove("show");
}
});
Data Polling is a very frequently used feature in web applications to fetch data from the server on a regular interval, and it's important for applications where data changes frequently, like a calendar application to show meetings, or a chat application to fetch new chats, or any application that requires real-time data.
π Live Code Example
/* HTML */
<h1>Polling from server</h1>
<button id="pollBtn">Poll data</button>
<button id="stopPollBtn">Stop Poll</button>
function startPolling(url, interval = 5000) {
const poll = async () => {
try {
const response = await fetch(url);
const data = await response.json();
console.log("Polled Data:", data);
} catch (error) {
console.error("Polling error:", error);
}
};
// Call immediately, then repeatedly
poll();
return setInterval(poll, interval);
}
let pollId = null;
const pollBtn = document.getElementById("pollBtn");
const stopPollBtn = document.getElementById("stopPollBtn");
pollBtn.addEventListener("click", () => {
// Start polling every 5 seconds
pollId = startPolling("https://jsonplaceholder.typicode.com/posts/1");
});
stopPollBtn.addEventListener("click", () => {
// To stop polling
clearInterval(pollId);
console.log("Polling Stopped !!");
});
In many machine coding questions, sometimes required to generate a random number between ranges, so it's important to know how to use A Math.random
function to understand the concept of random number generation between integer and float numbers. For example - Dice rolling game, flip the card game, and random starting point for an application.
function getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInteger(1, 100)); // ex - 35
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
console.log(getRandomFloat(1, 10)); // ex - 4.6345
Handling dates is not always straightforward when it comes to using in a Machine coding interview, so it's important to understand the most common cases that generally come into play in an interview - Difference between 2 dates and date formatting for questions like calendar.
Learn More - Understanding JavaScript Date Object with Examples
function getDateDifference(date1, date2) {
const diffMs = Math.abs(date2 - date1); // in milliseconds
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffMinutes = Math.floor(diffMs / (1000 * 60));
return {
days: diffDays,
hours: diffHours,
minutes: diffMinutes,
};
}
const date1 = new Date('2025-06-10');
const date2 = new Date('2025-06-13');
console.log(getDateDifference(date1, date2));
const now = new Date();
console.log(now.toLocaleDateString()); // "6/13/2025"
console.log(now.toLocaleTimeString()); // "10:23:45 AM"
console.log(now.toLocaleString()); // "6/13/2025, 10:23:45 AM"
Understanding common patterns is very important to ace a frontend machine coding round, so that you can handle any new machine coding problem in an interview very easily. All the patterns covered in the post are important for any machine coding question, like Listing logic, Search logic, API calls handling, Dates, Polling, Listing logic, etc.
We will be going to include many more patterns continuously in this post to make it the best cheat sheet to receive patterns before any Machine Coding Interview.
Happy Coding :)
Advertisement
Advertisement
Advertisement
Alok Kumar Giri
Last Updated Jun 2, 2025
Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.
Anuj Sharma
Last Updated Jun 27, 2025
A detailed list of 20+ most asked Frontend Machine Coding Interview Questions and resources both in JavaScript & React. Also covers expected functional/Non-functional requirements in this Interview.
Anuj Sharma
Last Updated Jan 29, 2025
Understand the difference between HTTP/2 vs HTTP/1.1 based on the various parameters, which helps to understand the improvement areas of HTTP/2 over HTTP 1.1
Akash Deep Chitransh
Last Updated May 26, 2025
Learn how to build and publish your own NPM package with Rollup, testing, and troubleshooting. Stay tuned for part 2: building a React state management library!
Anuj Sharma
Last Updated Jan 9, 2025
Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.
Anuj Sharma
Last Updated Jan 16, 2025
Deep dive into promise.all polyfill in javascript will help to understand the working of parallel promise calls using Promise.all and its implementation to handle parallel async API calls.
Β© 2024 FrontendGeek. All rights reserved