Blog/NotesConcept

Best Cheat Sheet for Frontend Machine Coding Interview Round

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.

Intermediate

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 

  1. Search Logic
    1. Search for a text in the Array of objects using Array.includes() or a Regex expression
    2. Accessibility Considerations for Search Boxes
  2. Listing Logic
    1. Responsive listing using flexbox/grid
    2. Product Catalog listing with images
    3. Infinite scroll using Intersection Observer
  3. API Calls
    1. 1️⃣ API calls using fetch - GET, POST, PATCH
    2. 2️⃣ Parallel API calls
  4. DOM - Event handling & Delegation
    1. 1️⃣ Event handling
    2. 2️⃣ Event Delegation
  5. Debouncing & Throttling
    1. 1️⃣ Debouncing
    2. 2️⃣ Throttling
  6. Media Queries - Responsive Design
  7. Modal/Menu Implementation - Absolute positioning
  8. API Data Polling
  9. Random Number Generation
    1. Generate a random number between a range of integers
    2. Generate a floating random number
  10. Date handling in JavaScript
    1. Difference between 2 dates
    2. Display date format

Frontend Machine Coding Interview Round: Cheat Sheet

Here are the important concepts to revise before every machine coding interview.

Search Logic

Related Questions

  1. Auto Complete Search or Type Ahead search

Search for a text in the Array of objects using 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);

Accessibility Considerations for Search Boxes

1️⃣ Search Box with Auto-suggestion

Live Code Example 

<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"
/>

Listing Logic

Related Questions

  1. Auto Complete Search or Type Ahead search
  2. News feed / Infinite scroll
  3. Pagination

Responsive listing using flexbox/grid

CodePen Live Example

/* 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);
});

Product Catalog listing with images

Codepen Live Example

  <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);
    });

Infinite scroll using Intersection observer

How it works in summary

  • Create a "loader" element at the bottom of the page.
  • IntersectionObserver watches this element.
  • When the element becomes visible (user scrolls near the bottom), more items are loaded.
  • New items push the loader again on the bottom, and the observer keeps triggering as needed.

Live Code Example

// 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;
}

API Calls

1️⃣ API calls using fetch - GET, POST, PATCH

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()

Live Code Example

/* 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

Live Code 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 πŸ‘‡πŸ‘‡

Live Code 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();
  }
});

2️⃣ Parallel API calls

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.

Live Code Example

/* 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.

Live Code Example

/* 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();

DOM - Event handling & Delegation

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

  1. Dynamic forms
  2. TODO lists
  3. Comment sections
  4. Games like tic-tac-toe

1️⃣ Event handling

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}`);
});

2️⃣ Event Delegation

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

  1. Games like tic-tac-toe
  2. Chess board
  3. Kanban board

Live Code Example

/* 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 & Throttling

1️⃣ Debouncing

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);

2️⃣ Throttling

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);

Media Queries - Responsive Design

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;
  }
}

Modal/Menu Implementation - Absolute positioning

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

  1. Context Menu component
  2. Menu bar with Menus
  3. Responsive Menu bar

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">&times;</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");
  }
});

API Data Polling

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 !!");
});

Random Number Generation

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.

Generate a random number between a range of integers

function getRandomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomInteger(1, 100));  // ex - 35

Generate a random float number

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

console.log(getRandomFloat(1, 10));  // ex - 4.6345

Date Handling in JavaScript

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

Difference between 2 Dates

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));

Format Dates to display

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 :) 

⏭️What Next

  1. Frontend Machine Coding Questions & Resources

Share this post now:

Advertisement

πŸ’¬ Comments (0)

Login to comment

Advertisement

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Advertisement


Other Related Blogs

Master Hoisting in JavaScript with 5 Examples

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.

20+ Frontend Machine Coding Interview Questions (JS + React)

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.

HTTP/2 vs HTTP/1.1: What's the Key Difference?

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

Part 1: From Zero to Published β€” How I Built and Published My First React NPM Package

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!

Understand JavaScript Date Object with Examples (for JavaScript Interviews)

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.

Promise.all Polyfill in JavaScript - Detailed Explanation [For Interviews]

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.

FrontendGeek
FrontendGeek

Β© 2024 FrontendGeek. All rights reserved