Newer ES features (ES7βES14): β includes(), ** (ES7) β async/await, Object.entries() (ES8) β Object rest/spread, Promise.finally (ES9) β Array.flat(), Object.fromEntries() (ES10) β BigInt, ?
Short answer: ?, ?. (ES11) replaceAll(), Promise.any() (ES12) at(), top-level await (ES13) Array.findLast(), findLastIndex() (ES14+) πΉ 76. includes() method for arrays (ES7) Checks if an array contains a specific element and returns true or false. const fruits = ["apple", "banana", "mango"]; console.log(fruits.includes("banana")); // trueβ¦ Explain a bitβ¦ moreβ¦β¦ console.log(fruits.includes("grapes")); // false πΉ 77. asyncβ¦
Explain a bit more
function fetchData() { try { const response = await fetch(" const data = await response.json(); console.log(data); } catch (err) { console.error(err); fetchData(); Notes: async marks a function as asynchronous and it returns a Promise.
Example code
fetch('/api/data') .then(res => res.json()) .catch(err => console.error(err)) .finally(() => console.log('Fetch attempt finished')); πΉ 83. Asynchronous iterators (ES9) Allow iterating over asynchronous data streams using for await...of. Example: async function* asyncGenerator() { yield await Promise.resolve(1); yield await Promise.resolve(2); yield await Promise.resolve(3); (async () => { for await (const num of asyncGenerator()) { console.log(num); })(); // Output: 1, 2, 3 πΉ 84. Array.flat() and Array.flatMap() (ES10) Array.flat(depth) β Flattens nested arrays up to the specified depth. Example: const arr = [1, [2, [3, 4]]]; console.log(arr.flat(1)); // [1, 2, [3, 4]] console.log(arr.flat(2)); // [1, 2, 3, 4] Array.flatMap() β Maps each element and flattens the result by one level. Example: const arr = [1, 2, 3]; const result = arr.flatMap(x => [x, x*2]); console.log(result); // [1, 2, 2, 4, 3, 6] πΉ 85. Object.fromEntries() (ES10) Converts an array of key-value pairs into an object. Example: const entries = [['name', 'Sandeep'], ['age', 30]]; const obj = Object.fromEntries(entries); console.log(obj); // {name: "Sandeep", age: 30} πΉ 86. Optional catch binding (ES10) Allows omitting the error parameter in catch if itβs not needed. Example: try { throw new Error("Oops"); } catch { console.log("Error handled without using the error object"); πΉ 87. BigInt (ES11 / 2020) Represents integers larger than Number.MAX_SAFE_INTEGER. Example: const bigNumber = 123456789012345678901234567890n; console.log(bigNumber + 1n); // 123456789012345678901234567891n Notes: Use n at the end to denote a BigInt literal. Cannot mix Number and BigInt directly in arithmetic. πΉ 88. Nullish coalescing operator ?? (ES11 / 2020) Returns the right-hand side value only if the left-hand side is null or undefined. Example: const name = null; console.log(name ?? "Default Name"); // "Default Name" const age = 0; console.log(age ?? 18); // 0 (not null or undefined) πΉ 89. Optional chaining ?. (ES11 / 2020) Safely accesses nested object properties without throwing an error if a property is null or undefined. Example: const user = { profile: { name: "Sandeep" } }; console.log(user.profile?.name); // "Sandeep" console.log(user.address?.city); // undefined (no error) πΉ 90. Promise.allSettled() (ES11 / 2020) Waits for all promises to settle (fulfilled or rejected) and returns an array of their results. Example: const promises = [Promise.resolve(1), Promise.reject("Error")]; Promise.allSettled(promises).then(results => console.log(results)); // [ // { status: "fulfilled", value: 1 }, // { status: "rejected", reason: "Error" } // ] πΉ 91. replaceAll() for strings (ES12 / 2021) Replaces all occurrences of a substring in a string. Example: const text = "JavaScript is fun. JavaScript is powerful."; console.log(text.replaceAll("JavaScript", "JS")); // "JS is fun. JS is powerful." Note: Unlike replace(), replaceAll() replaces every match, not just the first. πΉ 92. Promise.any() (ES12 / 2021) Returns the first fulfilled promise. Rejects only if all promises are rejected. Example: const promises = [ Promise.reject("Error1"), Promise.resolve(42), Promise.resolve(100) Promise.any(promises).then(result => console.log(result)); // 42 πΉ 93. Logical assignment operators (ES12 / 2021) Combine logical operations with assignment: &&=, ||=, ??=. Examples: let a = true; let b = false; // AND assignment a &&= false; console.log(a); // false // OR assignment b ||= true; console.log(b); // true // Nullish assignment let c = null; c ??= 10; console.log(c); // 10 πΉ 94. at() method for arrays and strings (ES13 / 2022) Returns the element at a specific index, supporting negative indexing. Example β Array: const arr = [10, 20, 30, 40]; console.log(arr.at(1)); // 20 console.log(arr.at(-1)); // 40 (last element) Example β String: const str = "JavaScript"; console.log(str.at(0)); // "J" console.log(str.at(-3)); // "i" πΉ 95. Top-level await (ES13 / 2022) Allows using await outside async functions in modules. Example: // In a module (ESM) const data = await fetch(" .then(res => res.json()); console.log(data); Notes: Works only in modules, not in regular scripts. Makes asynchronous initialization easier. πΉ 96. Object.hasOwn() (ES13 / 2022) Checks whether an object has a specific own property (safer than hasOwnProperty). Example: const obj = { name: "Sandeep" }; console.log(Object.hasOwn(obj, "name")); // true console.log(Object.hasOwn(obj, "age")); // false Advantage: Works even if hasOwnProperty is overwritten. πΉ 97. Array.findLast() and Array.findLastIndex() (ES14+ / 2023+) findLast() β Returns the last element in the array that satisfies the provided testing function. findLastIndex() β Returns the index of the last element that satisfies the test. Example β findLast(): const arr = [1, 2, 3, 4, 5, 6]; const lastEven = arr.findLast(x => x % 2 === 0); console.log(lastEven); // 6 Example β findLastIndex(): const arr = [1, 2, 3, 4, 5, 6]; const lastEvenIndex = arr.findLastIndex(x => x % 2 === 0); console.log(lastEvenIndex); // 5 πΉ 98. New built-in methods introduced recently (ES14+ / 2023+) Some useful new methods in modern JavaScript: Array.findLast() & Array.findLastIndex() β Already covered. Array.toSorted() β Returns a sorted copy of the array without mutating the original. const arr = [3, 1, 2]; const sortedArr = arr.toSorted(); console.log(sortedArr); // [1, 2, 3] console.log(arr); // [3, 1, 2] Array.toReversed() β Returns a reversed copy without mutating original. Array.toSpliced() β Returns a copy of the array with spliced elements removed or replaced. Array.with() β Returns a new array with an element replaced at a given index. String.toSorted(), String.toReversed() β Similar operations for strings. Note: These methods preserve immutability, unlike their older counterparts like sort() and reverse(). πΉ 99. What is the DOM? The Document Object Model (DOM) is a programmatic representation of a webpage, allowing JavaScript to read, manipulate, and modify HTML and CSS. Example: console.log(document.body); // Accesses the <body> element πΉ 100. Difference between innerHTML, innerText, and textContent innerHTML β Returns/sets HTML content, including tags. innerText β Returns/sets rendered text, respects CSS styles. textContent β Returns/sets all text, ignores CSS, faster than innerText. Example: const div = document.querySelector("#myDiv"); div.innerHTML = "<p>Hello</p>"; // Inserts <p>Hello</p> div.innerText = "<p>Hello</p>"; // Displays "<p>Hello</p>" div.textContent = "<p>Hello</p>"; // Displays "<p>Hello</p>" πΉ 101. How do you select DOM elements? Use selectors like: document.getElementById("id") document.getElementsByClassName("className") document.getElementsByTagName("tagName") document.querySelector(".className") document.querySelectorAll("div p") πΉ 102. Difference between getElementById and querySelector getElementById β Selects an element by its ID, returns one element. querySelector β Selects first matching element by CSS selector (ID, class, tag, etc.). Example: const el1 = document.getElementById("myDiv"); const el2 = document.querySelector("#myDiv"); // Same result πΉ 103. How do you create and append DOM elements? const div = document.createElement("div"); div.textContent = "Hello World"; document.body.appendChild(div); // Adds the div to body πΉ 104. How do you update styles using JavaScript? const div = document.querySelector("#myDiv"); div.style.backgroundColor = "lightblue"; div.style.fontSize = "20px"; πΉ 105. What is addEventListener? Attaches event listeners to DOM elements without overwriting existing ones. Example: const button = document.querySelector("#myButton"); button.addEventListener("click", () => { alert("Button clicked!"); }); πΉ 106. What is localStorage? localStorage allows you to store key-value pairs in the browser that persist even after the browser is closed. Example: localStorage.setItem("username", "Sandeep"); console.log(localStorage.getItem("username")); // "Sandeep" πΉ 107. What is sessionStorage? sessionStorage stores key-value pairs for the duration of a page session. Data is cleared when the tab or browser is closed. Example: sessionStorage.setItem("token", "abc123"); console.log(sessionStorage.getItem("token")); // "abc123" πΉ 108. Difference between localStorage and sessionStorage Feature localStorage sessionStorage Lifetime Persist after browser closes Cleared on tab/browser close Storage limit ~5-10 MB ~5 MB Scope Shared across tabs of the same origin Only available in the current tab πΉ 109. How do cookies work in JavaScript? Cookies are small pieces of data stored in the browser and sent to the server with each request. Example: // Set a cookie document.cookie = "username=Sandeep; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/"; // Read cookies console.log(document.cookie); πΉ 110. Difference between cookies and localStorage Feature Cookies localStorage Sent to server? Yes, with every HTTP request No, only client-side Storage size ~4 KB ~5-10 MB Expiry Can have expiration date Persistent until explicitly removed Accessibility Both client & server Client only πΉ 111. What is the BOM (Browser Object Model)? The Browser Object Model represents the browserβs window and environment, allowing JavaScript to interact with the browser itself (not the page content). Example: console.log(window.innerWidth); // Width of browser window console.log(window.navigator.userAgent); // Browser info πΉ 112. Difference between window and document window β Represents the browser window, contains the BOM, global functions, timers, and document. document β Represents the HTML page content, part of the DOM. Example: console.log(window.location.href); // Current URL console.log(document.title); // Page title πΉ 113. How do you use navigator and location objects? navigator β Provides browser information. console.log(navigator.userAgent); console.log(navigator.language); location β Provides URL info and allows navigation. console.log(location.href); // Full URL location.href = " // Redirects page πΉ 114. What is setTimeout() and setInterval()? setTimeout() β Executes a function once after a delay. setTimeout(() => console.log("Hello after 2s"), 2000); setInterval() β Executes a function repeatedly at intervals. setInterval(() => console.log("Repeating every 1s"), 1000); πΉ 115. How do you detect browser features? Feature detection ensures code runs only if a feature is supported. if ('geolocation' in navigator) { console.log("Geolocation is supported!"); } else { console.log("Geolocation not supported"); πΉ 116. What is a JavaScript module? A module is a file that encapsulates code (variables, functions, classes) and exports it so it can be imported into other files, promoting modularity and reusability. Example (module.js): export const pi = 3.14; export function area(radius) { return pi * radius * radius; Usage (main.js): import { pi, area } from './module.js'; console.log(area(5)); // 78.5 πΉ 117. What are named vs default exports? Named exports β Export multiple things with their names; must import using {}. export const x = 10; export const y = 20; // Import import { x, y } from './module.js'; Default export β Only one export per module; can import with any name. export default function greet() { console.log("Hello!"); } // Import import greetFunc from './module.js'; greetFunc(); // Hello! πΉ 118. How do ES6 modules differ from CommonJS? Feature ES6 Modules CommonJS Syntax import / export require / module.exports Loading Static (compile-time) Dynamic (runtime) Browser support Native in modern browsers Needs bundler (Webpack, Node.js) Tree shaking Supported Not supported πΉ 119. What is tree shaking? Tree shaking is a technique to remove unused code from a module during bundling, reducing file size. Example: // utils.js export function usedFunc() { return 1; } export function unusedFunc() { return 2; } // Only import usedFunc import { usedFunc } from './utils.js'; Bundler removes unusedFunc from the final bundle. πΉ 120. What is a memory leak in JavaScript? A memory leak occurs when memory that is no longer needed is not released, leading to increased memory usage and potential slowdowns. Example: let arr = []; function addToArray() { arr.push(new Array(1000000).fill('*')); // Keeps adding large arrays Memory keeps growing because references are not cleared. πΉ 121. How can you avoid memory leaks? Remove event listeners when not needed. Nullify references to large objects. Avoid global variables. Use WeakMap or WeakSet for temporary storage. Properly manage closures. πΉ 122. What is debouncing and throttling? Debouncing β Ensures a function runs only after a specified delay since the last call. Useful for input events. function debounce(func, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); Throttling β Ensures a function runs at most once every specified interval, useful for scroll or resize events. function throttle(func, limit) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; func.apply(this, args); πΉ 123. What is garbage collection? Garbage collection is the automatic process of freeing memory that is no longer referenced, handled by the JavaScript engine (e.g., V8). Example: let obj = { name: "Sandeep" }; obj = null; // Previous object is now eligible for garbage collection πΉ 124. What is event loop starvation? Event loop starvation occurs when long-running synchronous code blocks the event loop, preventing other tasks (like UI updates or async callbacks) from executing. Example: while(true) {} // Infinite loop blocks everything πΉ 125. What are best practices for writing efficient JavaScript? Minimize DOM manipulations. Use event delegation. Avoid global variables. Use debounce/throttle for frequent events. Leverage ES6+ features for clean and performant code. Use let/const instead of var. Optimize loops and array methods. πΉ 126. What is functional programming? Functional programming (FP) is a programming paradigm where functions are treated as first-class citizens and focus on pure functions, immutability, and avoiding side effects. Example: const add = (a, b) => a + b; // Pure function πΉ 127. What is immutability? Immutability means data cannot be changed after it is created. Instead, new objects or arrays are returned when updates are needed. Example: const arr = [1, 2, 3]; const newArr = [...arr, 4]; // Original arr remains unchanged πΉ 128. What are map(), filter(), and reduce()? map() β Creates a new array by transforming each element. [1,2,3].map(x => x*2); // [2,4,6] filter() β Creates a new array with elements that satisfy a condition. [1,2,3].filter(x => x>1); // [2,3] reduce() β Reduces array to a single value using a reducer function. [1,2,3].reduce((sum, x) => sum+x, 0); // 6 πΉ 129. What is function composition? Function composition combines multiple functions into a single function, passing the output of one as input to the next. Example: const double = x => x*2; const increment = x => x+1; const compose = (f, g) => x => f(g(x)); compose(double, increment)(3); // (3+1)*2 = 8 πΉ 130. What is currying? Currying transforms a function that takes multiple arguments into a sequence of functions each taking a single argument. Example: const add = a => b => a + b; add(2)(3); // 5 πΉ 131. What is partial application? Partial application pre-fills some arguments of a function to create a new function. Example: const multiply = (a, b) => a * b; const double = multiply.bind(null, 2); double(5); // 10 πΉ 132. What is a pure function? A pure function always returns the same output for the same input and has no side effects. Example: const square = x => x*x; // Pure πΉ 133. What is referential transparency? Referential transparency means an expression can be replaced by its value without changing the program behavior. Example: const x = 10; console.log(x + 5); // Can replace x with 10 directly πΉ 134. What is the difference between null and undefined? null β Explicitly assigned to indicate no value. undefined β Default value for uninitialized variables or missing properties. let a; // undefined let b = null; // explicitly no value πΉ 135. What is NaN? NaN stands for Not-a-Number, representing an invalid numeric operation. console.log("abc" * 2); // NaN πΉ 136. What is eval() and why is it dangerous? eval() executes a string as JavaScript code. It is dangerous because it can execute malicious code and cause security vulnerabilities. eval("2 + 3"); // 5 πΉ 137. What is strict mode ("use strict")? Strict mode enables stricter parsing and error handling in JavaScript, preventing unsafe actions like creating global variables accidentally. "use strict"; x = 5; // Error: x is not defined πΉ 138. What is a Symbol? Symbols are unique and immutable primitive values, often used as object property keys. const sym = Symbol('id'); const obj = { [sym]: 123 }; πΉ 139. What is a generator function? Generator functions use function* and can yield multiple values over time, allowing lazy evaluation. function* gen() { yield 1; yield 2; const g = gen(); console.log(g.next().value); // 1 πΉ 140. What is a WeakMap and WeakSet? WeakMap β Object keys are weakly referenced, helps avoid memory leaks. WeakSet β Set of objects with weak references. let wm = new WeakMap(); wm.set({}, 'value'); // Key can be garbage collected πΉ 141. What is tail call optimization? Tail call optimization allows recursive functions to reuse stack frames if the recursive call is the last operation. function factorial(n, acc = 1) { if (n === 0) return acc; return factorial(n - 1, n * acc); // Tail call πΉ 142. Difference between deep copy and shallow copy? Shallow copy β Copies top-level properties only, nested objects remain referenced. Deep copy β Copies entire object structure, no references. const obj = { a: 1, b: { c: 2 } }; const shallow = { ...obj }; const deep = JSON.parse(JSON.stringify(obj)); πΉ 143. What is JSON and how do you parse/serialize it? JSON β JavaScript Object Notation, a lightweight data interchange format. const obj = { name: "John" }; const str = JSON.stringify(obj); // serialize const parsed = JSON.parse(str); // parse πΉ 144. What are template literals? Template literals allow embedded expressions using backticks `. const name = "John"; console.log(`Hello ${name}`); // Hello John πΉ 145. Difference between synchronous and asynchronous code? Synchronous β Executes line by line, blocking further execution. Asynchronous β Executes non-blocking, allows other code to run while waiting. πΉ 146. What are modules and why are they useful? Modules allow splitting code into reusable files and encapsulation, improving maintainability. // math.js export const add = (a,b) => a+b; // main.js import { add } from './math.js'; πΉ 147. What is transpilation (Babel, TypeScript)? Transpilation converts modern JS/TypeScript code into older JavaScript compatible with older browsers. πΉ 148. What is Type Coercion in JavaScript? Type coercion is the automatic conversion between types. console.log('5' - 2); // 3 (string -> number) πΉ 149. How do you detect if a variable is an array? Array.isArray([1,2,3]); // true πΉ 150. What are polyfills? Polyfills implement features in older browsers that donβt support them. if (!Array.prototype.includes) { Array.prototype.includes = function(el) { return this.indexOf(el) !== -1; πΉ 151. How do you prevent global namespace pollution? Use IIFE or modules. Avoid global variables. (function(){ const x = 10; })(); πΉ 152. What are IIFEs (Immediately Invoked Function Expressions)? IIFE β A function that runs immediately after definition, often used for scoping. (function() { console.log("IIFE executed"); })();
Real-world example (ShopNest)
The checkout button uses async/await to call /api/orders, shows a spinner, and catches network errors with a toast.
Say this in the interview
- Define β one clear sentence (the short answer above).
- Example β relate it to a project like ShopNest or your real work.
- Trade-off β when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png