259 questions with answers
JavaScript rounds are where most frontend interviews start. Expect concept questions (closures, scope, this, prototypes, the event loop, promises) and coding questions where you implement a utility or polyfill such as debounce, Promise.all or deep clone. Every coding question here comes with tests you can run in the browser.
1.Array.prototype.filter
Implement Array.prototype.filter with thisArg support and correct handling of sparse arrays.
2.Array.prototype.flat
Implement Array.prototype.flat with a depth argument, hole removal and an iterative variant.
3.Array.prototype.map
Implement Array.prototype.map, keeping holes in sparse arrays and supporting thisArg.
4.Array.prototype.reduce
Implement Array.prototype.reduce, including the no-initial-value rules and sparse arrays.
5.Backbone Model
Build an observable Model class with defaults, get/set/unset, per-attribute change events, previous values and silent updates.
6.Cache Async (Deduplicate Requests)
Memoize an async function so concurrent calls share one in-flight promise, results expire after a TTL and failures are not cached.
7.classnames
Build a CSS class string from strings, numbers, nested arrays and conditional objects.
8.Curry
Turn a function of n arguments into one that can be called with those arguments one or several at a time.
9.Data Selection
Implement a small query function over an array of records: filtering, multi-key stable sorting, pagination and field projection.
10.Debounce
Delay invoking a function until a burst of calls has stopped for a given wait time.
11.Deep Clone
Make a deep copy of a JSON-like value so that no nested object or array is shared with the original.
12.Deep Equal
Decide whether two JSON-like values are structurally equal, comparing nested objects and arrays by content.
13.Event Emitter
Implement an EventEmitter class with on, off and emit, the observer pattern behind Node's events module and DOM events.
14.Event Emitter II
Extend an event emitter with once, unsubscribe handles, bulk off and listener counts, with well-defined behaviour during emit.
15.Flatten
Flatten a nested array to a given depth, recursively or with an explicit stack.
16.Function.prototype.bind
Implement Function.prototype.bind with partial application and correct behaviour under new.
17.Get
Safely read a nested value from an object by a dot/bracket path, falling back to a default.
18.getElementsByClassName
Find every descendant element that has all of the given class names by walking the DOM tree yourself.
19.getElementsByTagName
Return every descendant element with a given tag name (or all of them for "*") by traversing the DOM tree.
20.Group By
Group the elements of an array into arrays keyed by the result of an iteratee.
21.JSON.stringify
Reimplement JSON.stringify: escaping, undefined and function handling, toJSON, wrapper objects, cycles and BigInt errors.
22.List Format
Format a list of names into a readable sentence with options for sorting, de-duplication and an "and N others" cutoff.
23.LRU Cache
Implement a fixed-capacity cache that evicts the least recently used entry, with O(1) get and set.
24.Map Async
Map over a list with an async callback, running every call in parallel and keeping the results in input order.
25.Map Async with Limit
Map over a list with an async callback while never running more than a given number of calls at once.
26.Memoize
Cache a function's results by argument so repeated calls with the same input skip the work.
27.Middlewares
Compose async middleware functions into one onion-style pipeline where each step can run code before and after next().
28.Promise.all
Implement Promise.all: resolve with every result in order, or reject on the first failure.
29.Promise.any
Implement Promise.any: fulfill with the first success, or reject with an AggregateError.
30.Promise Implementation
Build a Promises/A+-style MyPromise with then, catch, finally, chaining and thenable adoption.
31.Promise Pool
Build a concurrency-limited task queue: tasks can be added at any time and at most N run at once.
32.Promise Timeout
Wrap a promise so it rejects with a TimeoutError if it doesn't settle in time, without leaking timers.
33.Promisify
Convert a Node-style callback function into one that returns a promise.
34.Pub/Sub Store (Mini Redux)
Implement createStore with getState, dispatch and subscribe: the core of Redux in about 50 lines.
35.Retry with Backoff
Retry a failing async operation with exponential backoff and a predicate that decides which errors are worth retrying.
36.Signals (Fine-Grained Reactivity)
Implement createSignal, createEffect, createMemo, batch and untrack with automatic dependency tracking and glitch-free updates.
37.Spreadsheet Evaluator
Build a spreadsheet engine: parse cell formulas, evaluate references and ranges, recompute dependents on change and detect cycles.
38.Squash Object
Flatten a nested object into a single level whose keys are dot-separated paths.
39.Table of Contents
Build a nested table of contents from the h1–h6 headings in a document, generating unique anchor ids and rendering it as nested lists.
40.Throttle
Limit a function to at most one call per wait window, with leading and trailing calls.
41.Undo/Redo History
Implement an undoable value with past and future stacks, redo invalidation, no-op detection and a bounded history size.
42.Unique Array
Remove duplicate values from an array while keeping the first occurrence of each, in order.
43.Query String Parse and Stringify
Parse a URL query string into an object (with repeated keys as arrays) and serialise it back, handling encoding, + as space and malformed input.
44.Virtual DOM Diff (Keyed Children)
Patch the real DOM from an old and a new virtual tree, reusing nodes by type and key and moving keyed children instead of recreating them.
45.Virtual DOM: createElement and render
Implement h() to build virtual DOM nodes and render() to turn them into real DOM, with attributes, styles, events and function components.
46.How do you abort a web request using `AbortController` in JavaScript?
Cancelling fetch with signals, timeouts, AbortSignal.any and cleaning up in effects.
47.What is async/await and how does it simplify asynchronous code?
Syntax over promises: sequential vs parallel awaits, error handling, top-level await and pitfalls.
48.What are the common pitfalls of using the `this` keyword?
Lost receivers, callbacks, nested functions, arrow methods on objects and class field trade-offs.
49.Explain the differences between CommonJS modules and ES modules in JavaScript
Static imports vs runtime require, live bindings, loading semantics, tree-shaking and interop in Node.
50.How do you handle errors in asynchronous operations?
try/catch with await, .catch, unhandled rejections, fetch HTTP errors, aggregation and retries.
51.What is the event loop? Explain the difference between the macrotask and microtask queues.
How JavaScript schedules callbacks, promises and rendering on a single thread.
52.How do you handle errors using try...catch blocks?
How try/catch works with sync and async code, and how to catch errors usefully.
53.How do you make an HTTP request using the Fetch API?
GET and POST with fetch, checking response.ok, timeouts and cancellation.
54.How do you import and export modules in JavaScript?
Named, default, namespace, re-export and dynamic imports, and live bindings.
55.What are the various data types in JavaScript?
The seven primitives plus objects, typeof quirks, and value vs reference semantics.
56.What are modules and why are they useful?
Scope isolation, explicit dependencies, tree shaking and code splitting with ES modules.
57.Explain the concept of lexical scoping
Scope decided by where code is written, the scope chain, and how it enables closures.
58.Explain the Observer pattern and its use cases
Subjects notifying subscribers: event emitters, EventTarget, stores and their pitfalls.
59.How is `Promise.all()` different from `Promise.allSettled()`?
Fail-fast vs wait-for-everything, result shapes, and where any and race fit in.
60.Explain the different states of a Promise
Pending, fulfilled and rejected, what settled and resolved really mean, and why state is immutable.
61.Explain the concept of scope in JavaScript
Global, module, function and block scope, the scope chain, shadowing and the temporal dead zone.
62.What are Sets and Maps and how are they used?
Unique-value collections and keyed collections with any key type, plus new Set methods.
63.How can you test asynchronous code in JavaScript?
Awaiting promises, asserting rejections, fake timers and waiting for UI updates.
64.Explain the difference between unit testing, integration testing, and end-to-end testing
Scope, speed, confidence and cost of each level, with front-end examples.
65.Explain the different ways the `this` keyword can be bound
Default, implicit, explicit and new binding, arrow functions, and the precedence between them.
66.What are Promises and how do they work?
Promise objects, chaining, error propagation, microtask scheduling and Promise.withResolvers.
67.What is the use of `Promise.all()`
Running independent async work in parallel, fail-fast semantics and concurrency limits.
68.How do you write unit tests for JavaScript code?
Arrange-act-assert, testing behaviour not implementation, isolation and edge cases.
69.Array.prototype.at
Implement Array.prototype.at, including negative indices and the spec's integer coercion rules.
70.Array.prototype.concat
Implement Array.prototype.concat, including sparse arrays and Symbol.isConcatSpreadable.
71.Async Queue with Priority
Run async tasks with a concurrency limit, starting higher-priority tasks first and keeping FIFO order within a priority.
72.Camel Case Keys
Deeply convert snake_case object keys from an API response into camelCase.
73.Cancellable Interval
Wrap setInterval so it returns a cancel function that stops future ticks.
74.Cancellable Timeout
Wrap setTimeout so it returns a cancel function instead of a timer id.
75.Chunk
Split an array into consecutive groups of a fixed size, with a shorter final group if needed.
76.Compose
Combine functions right to left into a single function, where each output feeds the next input.
77.Count By
Count how many elements of an array map to each key produced by an iteratee.
78.Curry II (with placeholders)
Curry a function so that arguments can be supplied in any order using a placeholder value.
79.Data Merging
Merge workout session records by user: sum durations and combine equipment lists without duplicates.
80.Debounce II
Debounce with leading, trailing and maxWait options, plus cancel and flush.
81.Deep Clone II
Deep clone values with circular references, shared references, Date, RegExp, Map, Set, symbols and prototypes.
82.Deep Map
Transform every leaf value in a nested object/array structure while preserving its shape.
83.Deep Merge
Recursively merge configuration objects without mutating the inputs, with clear rules for arrays and undefined.
84.Deep Omit
Remove the given keys from an object at every level of nesting, including inside arrays.
85.Dependency Injection Container
Build an IoC container with transient, singleton and scoped lifetimes, child scopes, overrides and circular-dependency detection.
86.Difference
Return the elements of an array that do not appear in any of the other given arrays.
87.Identical DOM Trees
Decide whether two DOM nodes are structurally identical: same tags, attributes, text and children, without using isEqualNode.
88.Feature Flag Evaluator
Evaluate feature flags with a kill switch, targeting rules and a percentage rollout that uses stable hashing so users keep their bucket.
89.Function.prototype.apply
Implement Function.prototype.apply, including array-like argument lists and argument validation.
90.Function.prototype.call
Implement Function.prototype.call without using call, apply or bind.
91.getElementsByStyle
Find descendant elements whose computed value for a CSS property equals a given value, normalising values like red vs #f00.
92.Has
Check whether an object has an own property at a nested path, even when the value is undefined.
93.HTML Serializer
Turn a plain-object element tree into pretty-printed, correctly escaped HTML with indentation and void elements.
94.instanceof
Re-implement the instanceof operator by walking the prototype chain.
95.Intersection
Return the unique values that appear in every one of the given arrays.
96.Is Empty
Decide whether a value is empty: no length, no size, or no own enumerable keys depending on its type.
97.jQuery Class Manipulation
Build a tiny $ wrapper with chainable addClass, removeClass, toggleClass and hasClass that work on every matched element.
98.jQuery CSS
Implement a $(selector).css() getter/setter that handles camelCase names, objects, automatic px units and removal.
99.JSON.parse (Lite)
Write a recursive-descent parser for JSON text that matches JSON.parse and throws SyntaxError on invalid input.
100.Make Counter
Use a closure to build independent counters that remember their own state between calls.
101.Max By
Return the element whose iteratee value is largest, skipping elements that produce no comparable value.
102.Memoize II (multiple arguments)
Memoize a function of any number of arguments with a collision-free cache keyed on every argument.
103.Min By
Return the element whose iteratee value is smallest, skipping elements that produce no comparable value.
104.new Operator
Re-implement the new operator: create the object, link the prototype, run the constructor.
105.Object.create
Implement Object.create, including null prototypes and property descriptors.
106.Observable
Build a minimal Observable with subscribe, unsubscribe, teardown, of/from creators and pipeable map and filter operators.
107.Omit
Create a shallow copy of an object without the listed keys.
108.Once
Wrap a function so that it runs at most once and later calls return the first result.
109.Partial
Pre-fill some of a function's arguments, with placeholders for positions supplied later.
110.Pick
Create a new object containing only the listed keys of a source object.
111.Pipe
Chain functions left to right so data flows through them in reading order.
112.Promise.allSettled
Implement Promise.allSettled: wait for every input and report each outcome in order.
113.Promise.race
Implement Promise.race: settle the same way as the first input to settle.
114.Promise.resolve
Implement Promise.resolve, including promise pass-through and thenable adoption.
115.Promise.withResolvers
Implement Promise.withResolvers to create a promise you can settle from outside its executor.
116.Promisify II
Extend promisify with a custom-implementation symbol, like Node's util.promisify.custom.
117.Range
Generate an array of numbers from start up to, but not including, end with an optional step.
118.Run Async Tasks in Series
Run a list of async functions one after another, passing each result to the next and stopping at the first failure.
119.Set
Write a value at a nested path, creating missing objects and arrays along the way.
120.setInterval with setTimeout
Re-implement setInterval and clearInterval using only chained setTimeout calls.
121.Sleep
Write a promise-based sleep(ms) and explain why it pauses an async function but not the thread.
122.Template Engine
Build a {{ }} interpolation engine with dotted paths, HTML escaping, raw {{{ }}} output, filters and a compile step.
123.Text Search Highlight
Wrap every case-insensitive match of the query words in <b> tags, merging overlapping and adjacent matches.
124.Type Utilities
Write reliable checks for JavaScript's primitive types, including the null and boxed-value traps.
125.Type Utilities II
Write type checks for non-primitive values: arrays, functions, objects and plain objects.
126.Union By
Merge several arrays into one list of unique elements, where uniqueness is decided by an iteratee.
127.How do you add, remove, and modify HTML elements using JavaScript?
createElement, append, replaceWith, remove, classList, fragments, templates and avoiding innerHTML XSS.
128.What are the benefits of using currying and partial application?
Reuse, configuration, composition and point-free pipelines, plus the costs.
129.Explain the concept of a callback function in asynchronous operations
Passing functions to be called later, error-first callbacks, callback hell and inversion of control.
130.Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?
To understand the differences between the two, let's look at what each function does.
131.Can you give an example for destructuring an object or an array?
Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct
132.Can you give an example of a curry function and why this syntax offers an advantage?
Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the re
134.How do you reliably determine whether an object is empty?
Own keys vs enumerable keys, symbols, prototypes, null and non-plain objects.
135.Explain the difference between classical inheritance and prototypal inheritance
Blueprint-copying classes vs live delegation to objects, and where JS classes fit.
136.How can closures be used to create private variables?
The module/factory pattern for encapsulation, and how it compares to #private class fields.
137.Explain the concept of code coverage and how it can be used to assess test quality
Line, branch and function coverage, what they miss, and mutation testing.
138.What is the Command pattern and how is it used?
Encapsulating actions as objects for undo/redo, queues, macros and keyboard shortcuts.
139.Create a for loop that iterates up to 100 while outputting **"fizz"** at multiples of 3, **"buzz"** at multiples of 5 and **"fizzbuzz"** at multiples of 3 and 5.
Check out this version of FizzBuzz by Paul Irish.
140.Provide some examples of how currying and partial application can be used
Practical uses: event handlers, loggers, validators, API clients and pipelines.
141.How do currying and partial application differ from each other?
Unary chains versus fixing some arguments once, with implementations of both.
142.How can you create custom error objects?
Subclassing Error with name, code and cause, and the instanceof caveats.
143.What is the Decorator pattern and how is it used?
Wrapping objects or functions to add behaviour, including higher-order functions and TC39 decorators.
144.Describe event bubbling.
When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the
145.Describe event capturing in JavaScript and browsers
The top-down phase of DOM event propagation and when listening in it is useful.
146.What are design patterns and why are they useful?
Reusable solutions to recurring design problems and a shared vocabulary for teams.
147.Difference between document load event and document DOMContentLoaded event?
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes
149.Explain the concept of error propagation in JavaScript
How errors unwind the call stack, flow through promise chains and reach global handlers.
151.What are event listeners and how are they used?
addEventListener options (capture, once, passive, signal), removal and memory hygiene.
152.Explain the event phases in a browser
Capture, target and bubble phases, eventPhase values, and how shadow DOM retargeting fits in.
153.Explain Ajax in as much detail as possible.
Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applicat
154.Explain event delegation
Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire w
155.Explain Function.prototype.bind.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any pro
156.Explain "hoisting".
Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their de
157.Explain how JSONP works (and how it's not really Ajax).
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-o
158.Explain how prototypal inheritance works
All JavaScript objects have a proto property with the exception of objects created with Object.create(null), that is a reference to another object, which is cal
159.Explain how this works in JavaScript
There's no simple explanation for this; it is one of the most confusing concepts in JavaScript. A hand-wavey explanation is that the value of this depends on ho
160.Explain the difference between mutable and immutable objects.
Immutability is a core principle in functional programming, and has lots to offer to object-oriented programs as well. A mutable object is an object whose state
161.Explain the difference between synchronous and asynchronous functions.
Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this
163.Explain the same-origin policy with regards to JavaScript.
The same-origin policy restricts how a document or script from one origin can interact with resources from another origin. Two URLs have the same origin when th
164.Explain what a single page app is and how to make one SEO-friendly.
The below is taken from the awesome Grab Front End Guide, which coincidentally, is written by me!
166.What is the Factory pattern and how is it used?
Creating objects through a function that hides construction details.
167.Have you ever used JavaScript templating? If so, what libraries have you used?
Yes. Handlebars, Underscore, Lodash, AngularJS, and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos wou
168.How can you share code between files?
This depends on the JavaScript environment.
169.How do you organize your code? (module pattern, classical inheritance?)
In the past, I've used Backbone for my models which encourages a more OOP approach, creating Backbone models and attaching methods to them.
170.How does JavaScript garbage collection work?
Reachability, mark-and-sweep, generational collection and how front-end apps leak memory.
171.Explain the concept of inheritance in ES2015 classes
extends, super, constructor rules, method overriding, statics and private fields in subclasses.
172.What is the difference between innerHTML and textContent?
How markup parsing, text nodes and innerText differ, and why textContent is the safe default.
173.What is the Intl namespace object for?
Locale-aware formatting of numbers, dates, plurals, lists, collation and segmentation.
174.What are iterators and generators in JavaScript and what are they used for?
The iteration protocols, function*, lazy sequences, async iteration and iterator helpers.
175.What are the different types of errors in JavaScript?
Built-in Error subclasses, DOMException, and useful ways to categorise failures.
176.What are some best practices for writing maintainable and effective tests in JavaScript?
Behaviour-focused, deterministic, readable tests that survive refactors.
177.Make this work:
Make this work:
178.How do you manipulate CSS styles using JavaScript?
Classes, custom properties, inline styles, computed styles and constructable stylesheets.
179.What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?
Weakly held keys, garbage collection, non-iterability, and real use cases like caches and private data.
180.What is the difference between a `Map` object and a plain object in JavaScript?
Key types, ordering, size, prototype pitfalls, performance and serialisation compared.
181.What are mocks and stubs and how are they used in testing?
Test doubles: stubs, mocks, spies and fakes, plus network mocking with MSW.
182.What is the Module pattern and how does it help with encapsulation?
IIFE closures, revealing module, ES modules and private class fields for encapsulation.
183.What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?
Why mouseenter does not bubble or fire for children, and when each is the right choice.
184.What are JavaScript object getters and setters for?
Computed properties, validation and encapsulation with get/set, plus their performance and debugging trade-offs.
185.Other Answers
- https://github.com/sudheerj/javascript-interview-questions
186.Explain the concept of partial application
Fixing some arguments of a function up front to create a more specific function.
187.What are the potential pitfalls of using closures?
Loop capture bugs, stale closures in React, retained memory and per-instance function costs.
188.What are some popular JavaScript testing frameworks?
Vitest, Jest, node:test, Testing Library, Playwright, Cypress and how they fit together.
189.How do you prevent the default behavior of an event?
preventDefault, cancelable events, passive listeners and when not to block defaults.
190.What is the difference between `event.preventDefault()` and `event.stopPropagation()`?
Cancelling the browser action vs stopping the event travelling, plus stopImmediatePropagation.
191.What are JavaScript object property flags and descriptors?
writable, enumerable, configurable, accessor descriptors and how freeze/seal build on them.
192.Explain the concept of the Prototype pattern
Creating objects from existing ones: Object.create, prototype sharing and cloning.
193.What is the purpose of the finally block?
Cleanup that runs on every exit path, Promise.finally, override gotchas and using declarations.
194.What is the purpose of the `new` keyword?
The four steps new performs, return-value rules, new.target and what cannot be constructed.
195.Explain the difference between `document.querySelector()` and `document.getElementById()`
Selector power vs a direct id lookup, scoping, live vs static collections and escaping.
196.How do you get the query string values of the current page in JavaScript?
Reading and updating query parameters safely with URLSearchParams and URL.
197.How do Sets and Maps handle equality checks for objects?
SameValueZero and reference identity for object keys, and how to dedupe by value.
198.What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?
Where each callback lands in the Node.js event loop, and the browser equivalents.
199.Explain the concept of the Singleton pattern
One shared instance, why ES modules already give you one, and the testing downsides.
200.Explain the concept of the Strategy pattern
Swapping interchangeable algorithms behind one interface, often as a map of functions.
201.Explain the concept of test-driven development (TDD)
Red-green-refactor, its benefits, costs and where it fits in front-end work.
202.Explain the concept of `this` binding in event handlers
this as currentTarget in listeners, arrows and bind, removing bound listeners and handleEvent objects.
203.What are the different types of testing in software development?
Functional and non-functional test types and how they fit a front-end strategy.
204.What are the various ways to create objects in JavaScript?
Object literals, constructors, classes, Object.create, factories and structuredClone compared.
205.What advantage is there for using the arrow syntax for a method in a constructor?
The main advantage of using an arrow function as a method inside a constructor is that the value of this gets set at the time of the function creation and can't
206.What are JavaScript polyfills for?
Filling missing APIs in older environments, how polyfills differ from transpilation, and their costs.
207.What are proxies in JavaScript used for?
Intercepting object operations with traps and Reflect: validation, reactivity, logging and their limits.
208.What are server-sent events?
One-way streaming over HTTP with EventSource: format, reconnection, limits and alternatives.
209.What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?
Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.
210.What are `Symbol`s used for in JavaScript?
Unique property keys, the global registry, and well-known symbols that hook into language behaviour.
211.What are the advantages and disadvantages of using Ajax?
- Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.
212.What are the benefits of using spread syntax and how is it different from rest syntax?
ES6's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create,
213.What are the differences between ES6 class and ES5 function constructors?
Let's first look at an example of each:
214.What are the differences between variables created using let, var or const?
Variables declared using the var keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. let
215.What are the pros and cons of using Promises instead of callbacks?
- Avoid callback hell which can be unreadable.
216.What are workers in JavaScript used for?
Dedicated, shared and service workers: off-main-thread work, messaging, transferables and limits.
217.What do you think of AMD vs CommonJS?
Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronou
218.What is a closure, and how/why would you use one?
A closure is the combination of a function and the lexical environment within which that function was declared. The word "lexical" refers to the fact that lexic
219.What is the definition of a higher-order function?
A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a res
220.What is the difference between == and ===?
== is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type convers
221.What is the DOM and how is it structured?
The live tree of nodes the browser builds from HTML, node types, and how it relates to rendering.
222.What is the extent of your experience with Promises and/or their polyfills?
Possess working knowledge of it. A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it's no
223.What is "use strict";? What are the advantages and disadvantages to using it?
'use strict' is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaS
225.What's a typical use case for anonymous functions?
They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.
227.What's the difference between an "attribute" and a "property"?
Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: <inp
228.What's the difference between .call and .apply?
Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-
230.What's the difference between host objects and native objects?
Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String, Math, RegExp, Object, Function, etc
231.What tools and techniques do you use for debugging JavaScript code?
- Good old console.log debugging
232.When would you use document.write()?
document.write() writes a string of text to a document stream opened by document.open(). When document.write() is executed after the page has loaded, it will ca
233.Why is extending built-in JavaScript objects not a good idea?
Extending a built-in/native JavaScript object means adding properties/functions to its prototype. While this may seem like a good idea at first, it is dangerous
234.Why is it called a Ternary expression, what does the word "Ternary" indicate?
"Ternary" indicates three, and a ternary expression accepts three operands, the test condition, the "then" expression and the "else" expression. Ternary express
236.Why might you want to create static class members?
Static class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referring to it
238.What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?
Promise-based fetch versus event-based XHR: errors, cancellation, streaming, progress and cookies.
239.Array.prototype.square
Add a square() method to every array that returns a new array of squared values.
240.Clamp
Restrict a number to an inclusive range between a lower and an upper bound.
241.Compact
Return a new array with every falsy value removed.
242.Drop Right While
Drop trailing elements of an array for as long as a predicate holds, scanning from the end.
243.Drop While
Drop leading elements of an array for as long as a predicate holds, then keep the rest.
244.Fill
Overwrite a range of an array with a value, supporting negative start and end indices.
245.Find Index
Return the index of the first element that satisfies a predicate, starting from an optional index.
246.Find Last Index
Return the index of the last element that satisfies a predicate, searching backwards from an optional index.
247.From Pairs
Build an object from an array of [key, value] pairs, the inverse of Object.entries.
248.In Range
Check whether a number lies in a half-open range, with an optional start and swapped bounds.
249.Mean
Compute the arithmetic mean of an array of numbers, returning NaN for an empty array.
250.Number of Arguments
Return how many arguments a function was called with, and explain arguments vs rest vs Function.length.
251.Promise.reject
Implement Promise.reject and explain why it never unwraps promises or thenables.
252.Range Right
Generate the same numbers as range(start, end, step) but in descending order of generation.
253.Size
Return the size of a collection: length for arrays and strings, size for Map and Set, key count for objects.
254.String Repeat and Pad
Implement repeat, padStart and padEnd without the built-in string methods, matching their edge-case behaviour.
255.How do you convert a Set to an array in JavaScript?
Spread, Array.from and when you might not need to convert at all.
256.How do you create a constructor function?
Writing a constructor, putting methods on the prototype, guarding against missing new, and the class equivalent.
257.What are some tools that can be used for JavaScript testing?
The wider testing toolbox: runners, DOM utilities, mocking, browsers, visual, a11y and static checks.