Mid From PDF JavaScript JavaScript

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

  1. Define β€” one clear sentence (the short answer above).
  2. Example β€” relate it to a project like ShopNest or your real work.
  3. Trade-off β€” when you would not use it.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content onlyβ€”not admin or internal tools.

care@toolliyo.com

Need callback? Share your details