До бібліотеки
АнглійськаInterview180 карток

Interview 2 — JavaScript

180 common interview questions in English. Fundamentals, closures, objects, async code, browser APIs, testing, and coding exercises. Short answers for further study.

Крок за кроком

0 із 180 карток позначено «Знаю» у цьому демо.

Interview questions

Answer aloud, then check the short answer. Search by question or topic.

01

What is JavaScript, and how is it related to ECMAScript?

Topic: Language basics and types

SHORT ANSWER

JavaScript is a programming language; ECMAScript is the standard defining its core behavior.

02

How is JavaScript different from Java?

Topic: Language basics and types

SHORT ANSWER

They are separate languages. Similar names do not imply the same type system, runtime, or object model.

03

What are JavaScript's primitive types?

Topic: Language basics and types

SHORT ANSWER

Undefined, null, boolean, number, bigint, string, and symbol.

04

How do primitive values differ from objects?

Topic: Language basics and types

SHORT ANSWER

Primitives are immutable values. Objects have identity and can contain mutable properties.

05

What does it mean that JavaScript is dynamically typed?

Topic: Language basics and types

SHORT ANSWER

Values have types; a variable can hold values of different types over time.

06

What is the difference between null and undefined?

Topic: Language basics and types

SHORT ANSWER

Null usually expresses intentional absence; undefined commonly means a value has not been provided.

07

How do you check a value's type?

Topic: Language basics and types

SHORT ANSWER

Use typeof for most primitives, Array.isArray for arrays, and value === null for null.

08

Why does typeof null return 'object'?

Topic: Language basics and types

SHORT ANSWER

It is a historical language quirk. Null is still a primitive.

09

What is NaN, and how do you check for it?

Topic: Language basics and types

SHORT ANSWER

NaN represents an invalid numeric result. Number.isNaN(value) checks without coercion.

10

What is the difference between Number.isNaN() and isNaN()?

Topic: Language basics and types

SHORT ANSWER

Number.isNaN checks the value directly; global isNaN converts it to a number first.

11

What are truthy and falsy values?

Topic: Language basics and types

SHORT ANSWER

Falsy: false, 0, -0, 0n, empty string, null, undefined, NaN; also legacy document.all in browsers. Other values are truthy.

12

Are empty arrays and empty objects truthy?

Topic: Language basics and types

SHORT ANSWER

Yes. Their emptiness does not affect their boolean conversion.

13

What is a Symbol used for?

Topic: Language basics and types

SHORT ANSWER

A unique primitive often used as a property key or to customize built-in protocols.

14

When would you use BigInt?

Topic: Language basics and types

SHORT ANSWER

For integers beyond Number's safe range. Most arithmetic cannot mix BigInt and Number directly.

15

Why is 0.1 + 0.2 not exactly 0.3?

Topic: Language basics and types

SHORT ANSWER

Binary floating-point cannot represent these decimals exactly. Compare using a tolerance appropriate to the calculation.

16

What is the difference between var, let, and const?

Topic: Variables, scope, and operators

SHORT ANSWER

Var is function- or global-scoped; let and const are block-scoped. Const prevents reassignment.

17

Does const make an object immutable?

Topic: Variables, scope, and operators

SHORT ANSWER

No. It prevents rebinding the variable; the object's properties may still change.

18

What are global scope, function scope, and block scope?

Topic: Variables, scope, and operators

SHORT ANSWER

They determine where a binding is accessible: globally, within a function, or within a block.

19

What is lexical scope?

Topic: Variables, scope, and operators

SHORT ANSWER

A function's access to outer bindings depends on where it is defined in the source.

20

What is hoisting?

Topic: Variables, scope, and operators

SHORT ANSWER

Declarations affect bindings before their source line runs; initialization rules differ by declaration type.

21

What is the temporal dead zone?

Topic: Variables, scope, and operators

SHORT ANSWER

The period from entering a scope until a let, const, or class binding is initialized; accessing it throws.

22

What is variable shadowing?

Topic: Variables, scope, and operators

SHORT ANSWER

An inner binding uses the same name as an outer binding, hiding it within that scope.

23

What is the difference between == and ===?

Topic: Variables, scope, and operators

SHORT ANSWER

== may convert types; === compares without type coercion. Objects are compared by identity.

24

How does Object.is() differ from ===?

Topic: Variables, scope, and operators

SHORT ANSWER

Object.is treats NaN as equal to itself and distinguishes +0 from -0.

25

What is implicit type coercion?

Topic: Variables, scope, and operators

SHORT ANSWER

JavaScript automatically converts a value for an operation, such as converting a number during string concatenation.

26

What is the difference between logical OR (||) and nullish coalescing (??)?

Topic: Variables, scope, and operators

SHORT ANSWER

|| falls back for any falsy value; ?? falls back only for null or undefined.

27

What does optional chaining do?

Topic: Variables, scope, and operators

SHORT ANSWER

?. returns undefined if the value being accessed is null or undefined, instead of continuing that access.

28

What is short-circuit evaluation?

Topic: Variables, scope, and operators

SHORT ANSWER

&&, ||, and ?? evaluate the right operand only when needed and return an operand value.

29

What is the difference between rest and spread syntax?

Topic: Variables, scope, and operators

SHORT ANSWER

Rest collects remaining values; spread expands an iterable or copies an object's own enumerable properties.

30

What are destructuring and template literals?

Topic: Variables, scope, and operators

SHORT ANSWER

Destructuring extracts values into bindings; template literals support interpolation and multiline strings.

31

How does a function declaration differ from a function expression?

Topic: Functions and closures

SHORT ANSWER

A declaration initializes its function before execution in its scope; an expression creates a function when evaluated.

32

How do arrow functions differ from regular functions?

Topic: Functions and closures

SHORT ANSWER

Arrows capture surrounding this and arguments, cannot be constructors, and have no own prototype property.

33

What does it mean that functions are first-class values?

Topic: Functions and closures

SHORT ANSWER

They can be assigned, passed as arguments, and returned from other functions.

34

What is a higher-order function?

Topic: Functions and closures

SHORT ANSWER

A function that accepts functions, returns a function, or both.

35

What is a callback function?

Topic: Functions and closures

SHORT ANSWER

A function passed to another operation to be invoked; callbacks can be synchronous or asynchronous.

36

What is a closure?

Topic: Functions and closures

SHORT ANSWER

A function together with access to its surrounding lexical bindings, even after the outer function returns.

37

When are closures useful?

Topic: Functions and closures

SHORT ANSWER

For private state, configured callbacks, function factories, and remembering values between calls.

38

Why can var cause unexpected results in loop callbacks?

Topic: Functions and closures

SHORT ANSWER

Callbacks share one var binding. Let creates a separate binding for each loop iteration.

39

What is an immediately invoked function expression (IIFE)?

Topic: Functions and closures

SHORT ANSWER

A function expression called immediately, often to create a private scope.

40

What is a pure function?

Topic: Functions and closures

SHORT ANSWER

A function whose result depends only on its inputs and that causes no observable side effects.

41

What is a side effect?

Topic: Functions and closures

SHORT ANSWER

An observable change outside a function's returned value, such as mutation, logging, or a network request.

42

What is currying?

Topic: Functions and closures

SHORT ANSWER

Transforming a function with multiple arguments into a sequence of functions taking one argument each.

43

What is the difference between currying and partial application?

Topic: Functions and closures

SHORT ANSWER

Currying changes the calling structure; partial application fixes some arguments to produce a new function.

44

What is memoization?

Topic: Functions and closures

SHORT ANSWER

Caching results by input to avoid repeated work; consider cache size and changing dependencies.

45

What is recursion, and what can go wrong with it?

Topic: Functions and closures

SHORT ANSWER

A function calls itself on a smaller problem. Missing termination or excessive depth can overflow the stack.

46

How is this determined in a regular function?

Topic: This, prototypes, and classes

SHORT ANSWER

By how it is called: as a method, constructor, explicit binding, or plain call.

47

What is this in a plain function call in strict mode?

Topic: This, prototypes, and classes

SHORT ANSWER

Undefined, unless the function is bound; arrow functions instead capture their surrounding this.

48

What happens to this when you pass an object method as a callback?

Topic: This, prototypes, and classes

SHORT ANSWER

The original receiver is lost unless the caller supplies it; bind it or wrap the call.

49

What is the difference between call(), apply(), and bind()?

Topic: This, prototypes, and classes

SHORT ANSWER

Call and apply invoke with a chosen this; apply takes array-like arguments. Bind returns a bound function.

50

What does the new operator do?

Topic: This, prototypes, and classes

SHORT ANSWER

Creates an object, links its prototype, and calls the constructor with that this; an explicit object return can replace it.

51

What is the prototype chain?

Topic: This, prototypes, and classes

SHORT ANSWER

Property lookup checks an object, then successive prototypes, until a match or null.

52

What is the difference between a constructor's prototype and an object's prototype?

Topic: This, prototypes, and classes

SHORT ANSWER

The constructor's .prototype usually becomes the internal prototype of instances created with new.

53

How do you create an object with a specific prototype?

Topic: This, prototypes, and classes

SHORT ANSWER

Use Object.create(proto); Object.create(null) creates an object without a prototype.

54

How do JavaScript classes relate to prototypes?

Topic: This, prototypes, and classes

SHORT ANSWER

Classes provide syntax and rules over prototype-based inheritance; instance methods normally live on the prototype.

55

What do extends and super do?

Topic: This, prototypes, and classes

SHORT ANSWER

Extends establishes inheritance; super accesses parent behavior and calls the parent constructor in a derived constructor.

56

What is the difference between instance methods and static methods?

Topic: This, prototypes, and classes

SHORT ANSWER

Instance methods are called on instances; static methods are called on the class itself.

57

How do private class fields work?

Topic: This, prototypes, and classes

SHORT ANSWER

Fields beginning with # are only accessible from permitted code inside the declaring class.

58

What are getters and setters?

Topic: This, prototypes, and classes

SHORT ANSWER

Accessor functions that run when a property is read or assigned.

59

What does instanceof check?

Topic: This, prototypes, and classes

SHORT ANSWER

Normally, whether a constructor's prototype appears in the object's prototype chain; cross-realm checks can surprise you.

60

When might you prefer composition over inheritance?

Topic: This, prototypes, and classes

SHORT ANSWER

When behavior is easier to combine through smaller objects or functions than a rigid class hierarchy.

61

Are objects passed by reference in JavaScript?

Topic: Objects and copying

SHORT ANSWER

Arguments are passed by value. An object value is a reference: mutation is shared, parameter reassignment is not.

62

What is the difference between shallow and deep copying?

Topic: Objects and copying

SHORT ANSWER

A shallow copy shares nested objects; a deep copy recreates supported nested data.

63

How can you make a shallow copy of an object?

Topic: Objects and copying

SHORT ANSWER

Use { ...object } or Object.assign({}, object); nested values remain shared.

64

When would you use structuredClone()?

Topic: Objects and copying

SHORT ANSWER

To deeply clone supported data, including cycles, Maps, and Dates; functions and DOM nodes are not supported.

65

Why is JSON.parse(JSON.stringify(value)) not a general deep clone?

Topic: Objects and copying

SHORT ANSWER

It loses unsupported values and types, fails on cycles, and normally throws on BigInt.

66

How do you check whether an object has its own property?

Topic: Objects and copying

SHORT ANSWER

Use Object.hasOwn(object, key); the in operator also checks inherited properties.

67

What do Object.keys(), Object.values(), and Object.entries() return?

Topic: Objects and copying

SHORT ANSWER

Arrays of own enumerable string-keyed property names, values, or key-value pairs.

68

How do you convert key-value pairs into an object?

Topic: Objects and copying

SHORT ANSWER

Use Object.fromEntries(iterableOfPairs).

69

What is the difference between dot and bracket property access?

Topic: Objects and copying

SHORT ANSWER

Dot uses a fixed identifier; brackets accept an expression, including dynamic strings and symbols.

70

How do you remove a property from an object?

Topic: Objects and copying

SHORT ANSWER

Use delete object.key; assigning undefined keeps the property present.

71

What is the difference between Object.freeze() and Object.seal()?

Topic: Objects and copying

SHORT ANSWER

Both prevent adding or removing properties; freeze also makes data properties nonwritable. Both are shallow.

72

What are property descriptors?

Topic: Objects and copying

SHORT ANSWER

Metadata controlling writability, enumerability, configurability, or getter/setter behavior.

73

How do you compare two objects for equality?

Topic: Objects and copying

SHORT ANSWER

=== checks identity. Comparing contents requires a definition of equality and a suitable comparison function.

74

What is the difference between JSON and a JavaScript object?

Topic: Objects and copying

SHORT ANSWER

JSON is a text data format with limited types; objects are runtime values that can contain behavior.

75

What are Proxy and Reflect used for?

Topic: Objects and copying

SHORT ANSWER

Proxy intercepts object operations; Reflect provides functions for performing many of those operations.

76

How do map(), forEach(), and filter() differ?

Topic: Arrays, strings, and collections

SHORT ANSWER

Map transforms into a new array; forEach visits elements and returns undefined; filter selects matching elements.

77

What does reduce() do?

Topic: Arrays, strings, and collections

SHORT ANSWER

Combines elements into an accumulator. An explicit initial value handles empty arrays safely.

78

How do find(), findIndex(), some(), and every() differ?

Topic: Arrays, strings, and collections

SHORT ANSWER

Find returns the first match; findIndex its index; some checks any match; every checks all.

79

What is the difference between slice() and splice()?

Topic: Arrays, strings, and collections

SHORT ANSWER

Slice copies a range; splice changes the original array by removing, replacing, or inserting elements.

80

Which common array methods mutate the original array?

Topic: Arrays, strings, and collections

SHORT ANSWER

Push, pop, shift, unshift, splice, sort, reverse, fill, and copyWithin.

81

How do you sort numbers correctly?

Topic: Arrays, strings, and collections

SHORT ANSWER

Use numbers.sort((a, b) => a - b); default sorting compares string representations.

82

How do you sort or reverse an array without mutating it?

Topic: Arrays, strings, and collections

SHORT ANSWER

Use toSorted()/toReversed(), or copy first and then sort/reverse.

83

What is the difference between for...in and for...of?

Topic: Arrays, strings, and collections

SHORT ANSWER

For...in visits enumerable string property keys, including inherited ones; for...of consumes iterable values.

84

What is the difference between Map and a plain object?

Topic: Arrays, strings, and collections

SHORT ANSWER

Map accepts arbitrary keys, exposes size, and is directly iterable; object property keys are strings or symbols.

85

What is a Set used for?

Topic: Arrays, strings, and collections

SHORT ANSWER

Storing unique values and checking membership; distinct objects remain distinct even with identical contents.

86

How do WeakMap and WeakSet differ from Map and Set?

Topic: Arrays, strings, and collections

SHORT ANSWER

Weak collections do not keep their weakly held keys/values alive and cannot be enumerated.

87

What are iterables, iterators, and generators?

Topic: Arrays, strings, and collections

SHORT ANSWER

Iterables provide an iterator; iterators return next results; generators use function* and yield to produce them.

88

Are JavaScript strings mutable?

Topic: Arrays, strings, and collections

SHORT ANSWER

No. String operations return new values; indexed assignment does not change a string.

89

How do split(), join(), and trim() differ?

Topic: Arrays, strings, and collections

SHORT ANSWER

Split turns a string into an array; join combines array elements; trim removes surrounding whitespace.

90

What do regular expressions do, and how do you test a match?

Topic: Arrays, strings, and collections

SHORT ANSWER

They describe text patterns. Use regex.test(text) for a boolean; match or exec for match details.

91

What is the difference between synchronous and asynchronous code?

Topic: Promises and async functions

SHORT ANSWER

Synchronous steps finish in sequence; asynchronous operations allow a result to be handled later.

92

What is a Promise, and what states can it have?

Topic: Promises and async functions

SHORT ANSWER

It represents an eventual outcome: pending, fulfilled, or rejected. Settled means fulfilled or rejected.

93

Does a Promise executor run synchronously?

Topic: Promises and async functions

SHORT ANSWER

Yes. The function passed to new Promise runs immediately; .then handlers run asynchronously.

94

How does Promise chaining work?

Topic: Promises and async functions

SHORT ANSWER

Each .then returns a new promise that adopts the handler's returned value or promise, or rejects if it throws.

95

What do catch() and finally() do?

Topic: Promises and async functions

SHORT ANSWER

Catch handles rejection; finally runs cleanup and normally preserves the outcome unless it throws or returns a rejecting promise.

96

What does an async function return?

Topic: Promises and async functions

SHORT ANSWER

Always a promise: returned values fulfill it; uncaught throws reject it.

97

What does await do?

Topic: Promises and async functions

SHORT ANSWER

Pauses that async function or module until a value settles; it does not block the whole JavaScript thread.

98

How do you handle errors with async/await?

Topic: Promises and async functions

SHORT ANSWER

Use try/catch around awaited operations, or let rejection propagate to a caller that handles it.

99

What does Promise.all() do?

Topic: Promises and async functions

SHORT ANSWER

Collects results in input order; rejects on the first rejection. It does not cancel the remaining operations.

100

What does Promise.allSettled() do?

Topic: Promises and async functions

SHORT ANSWER

Waits for all inputs to settle and returns each fulfillment value or rejection reason.

101

How do Promise.race() and Promise.any() differ?

Topic: Promises and async functions

SHORT ANSWER

Race follows the first settlement; any follows the first fulfillment and rejects only if all reject.

102

How do you run independent async operations concurrently?

Topic: Promises and async functions

SHORT ANSWER

Start them before awaiting their combined results, often with Promise.all.

103

Why does await array.forEach(async callback) not wait for the callbacks?

Topic: Promises and async functions

SHORT ANSWER

ForEach ignores callback return values. Use for...of for sequencing or Promise.all(array.map(...)) for concurrency.

104

What happens if you forget to return a promise inside a .then handler?

Topic: Promises and async functions

SHORT ANSWER

The chain cannot wait for that operation or track its outcome unless you return or otherwise handle it.

105

How do you cancel an asynchronous request?

Topic: Promises and async functions

SHORT ANSWER

For fetch, pass an AbortSignal and call its controller's abort(). Promises themselves have no universal cancellation method.

106

What does it mean that JavaScript is single-threaded?

Topic: Event loop, timers, and errors

SHORT ANSWER

One agent runs one piece of JavaScript at a time; hosts and workers can perform other work concurrently.

107

What is the call stack?

Topic: Event loop, timers, and errors

SHORT ANSWER

The stack of active function calls; a call pushes a frame, and returning removes it.

108

What does the event loop do?

Topic: Event loop, timers, and errors

SHORT ANSWER

Coordinates queued work with JavaScript execution, letting asynchronous callbacks run when execution can proceed.

109

What is the difference between a task and a microtask in a browser?

Topic: Event loop, timers, and errors

SHORT ANSWER

Timers and events queue tasks; promise reactions queue microtasks, drained at checkpoints before the next task.

110

Does setTimeout(fn, 0) execute fn immediately?

Topic: Event loop, timers, and errors

SHORT ANSWER

No. It schedules a later task; current execution and queued microtasks run first.

111

Is setTimeout guaranteed to run at the requested time?

Topic: Event loop, timers, and errors

SHORT ANSWER

No. The delay is a threshold; busy execution and browser throttling can postpone it.

112

What is the difference between setInterval and recursive setTimeout?

Topic: Event loop, timers, and errors

SHORT ANSWER

SetInterval schedules repeatedly; recursive setTimeout can schedule the next run after the previous work completes.

113

When would you use requestAnimationFrame()?

Topic: Event loop, timers, and errors

SHORT ANSWER

For visual updates aligned with the browser's rendering cycle; use its timestamp for animation progress.

114

How can a long-running loop affect a web page?

Topic: Event loop, timers, and errors

SHORT ANSWER

It blocks the main thread, delaying input, rendering, and callbacks.

115

What is a Web Worker?

Topic: Event loop, timers, and errors

SHORT ANSWER

A separate execution context for background JavaScript; it communicates through messages and cannot directly access the DOM.

116

Can recursive microtasks make a page unresponsive?

Topic: Event loop, timers, and errors

SHORT ANSWER

Yes. Continually queueing microtasks can delay tasks and rendering.

117

What do try, catch, and finally do?

Topic: Event loop, timers, and errors

SHORT ANSWER

Try runs code, catch handles thrown errors, and finally performs cleanup as control leaves the construct.

118

Can try/catch around setTimeout catch an error thrown inside its callback?

Topic: Event loop, timers, and errors

SHORT ANSWER

No. The callback runs later; catch inside it or propagate the error through a handled promise.

119

How do Error, TypeError, and ReferenceError differ?

Topic: Event loop, timers, and errors

SHORT ANSWER

Error is general; TypeError signals an invalid type-related operation; ReferenceError signals an invalid binding reference.

120

Why should you avoid silently swallowing errors?

Topic: Event loop, timers, and errors

SHORT ANSWER

It hides failures and can leave invalid state. Recover explicitly or report and propagate with useful context.

121

What is the DOM?

Topic: DOM and browser events

SHORT ANSWER

The browser's object representation of a document, which scripts can inspect and change.

122

How do querySelector() and querySelectorAll() differ?

Topic: DOM and browser events

SHORT ANSWER

QuerySelector returns the first match or null; querySelectorAll returns a static NodeList of matches.

123

What is the difference between a live and a static DOM collection?

Topic: DOM and browser events

SHORT ANSWER

A live collection updates with DOM changes; a static collection preserves its membership from query time.

124

How do textContent, innerText, and innerHTML differ?

Topic: DOM and browser events

SHORT ANSWER

TextContent handles text; innerText reflects rendered text; innerHTML parses or serializes markup.

125

How do you create and insert a DOM element?

Topic: DOM and browser events

SHORT ANSWER

Use document.createElement(), set properties, then append or insert it into the document.

126

What are event capturing and bubbling?

Topic: DOM and browser events

SHORT ANSWER

Capturing travels toward the target; bubbling travels back through ancestors for events that bubble.

127

What is event delegation?

Topic: DOM and browser events

SHORT ANSWER

An ancestor handles descendant events, often using closest() to identify the relevant child.

128

What is the difference between event.target and event.currentTarget?

Topic: DOM and browser events

SHORT ANSWER

Target identifies the event's target; currentTarget is the element whose listener is currently running.

129

How do preventDefault() and stopPropagation() differ?

Topic: DOM and browser events

SHORT ANSWER

PreventDefault cancels a cancelable default action; stopPropagation stops travel to other nodes.

130

How does stopImmediatePropagation() differ from stopPropagation()?

Topic: DOM and browser events

SHORT ANSWER

It also prevents later listeners for that event on the same element.

131

How do you remove an event listener?

Topic: DOM and browser events

SHORT ANSWER

Use removeEventListener with the same type, function, and capture value, or abort its registered signal.

132

What does a passive event listener mean?

Topic: DOM and browser events

SHORT ANSWER

It promises not to call preventDefault(), allowing the browser to handle actions such as scrolling without waiting for cancellation.

133

What is the difference between DOMContentLoaded and load?

Topic: DOM and browser events

SHORT ANSWER

DOMContentLoaded follows parsing and deferred/module script execution; window load also waits for dependent resources such as images.

134

How do classic scripts with async and defer differ?

Topic: DOM and browser events

SHORT ANSWER

Async executes when ready without ordering guarantees; defer executes after parsing in document order, before DOMContentLoaded.

135

What is the difference between debouncing and throttling?

Topic: DOM and browser events

SHORT ANSWER

Debouncing groups nearby calls, often waiting for quiet; throttling limits execution frequency over time.

136

How do you request and read JSON with fetch()?

Topic: Requests, storage, and security

SHORT ANSWER

Await fetch, check response.ok, then await response.json(); handle request and parsing failures.

137

Does fetch reject its promise for HTTP 404 or 500?

Topic: Requests, storage, and security

SHORT ANSWER

No. HTTP error responses normally fulfill it; check response.ok or status yourself.

138

How do you send JSON in a POST request?

Topic: Requests, storage, and security

SHORT ANSWER

Set method to POST, Content-Type to application/json, and body to JSON.stringify(data).

139

What is CORS?

Topic: Requests, storage, and security

SHORT ANSWER

A browser protocol where server headers determine whether scripts may read cross-origin responses.

140

Why is mode: 'no-cors' not a general fix for CORS errors?

Topic: Requests, storage, and security

SHORT ANSWER

It usually produces an opaque response whose body and status JavaScript cannot read.

141

What defines a web origin?

Topic: Requests, storage, and security

SHORT ANSWER

The combination of scheme, hostname, and port.

142

How do localStorage, sessionStorage, and cookies differ?

Topic: Requests, storage, and security

SHORT ANSWER

LocalStorage persists; sessionStorage is scoped to a tab's session; matching cookies can be sent automatically with requests.

143

When would you use IndexedDB instead of localStorage?

Topic: Requests, storage, and security

SHORT ANSWER

For larger structured data and asynchronous transactions; localStorage is synchronous and stores strings.

144

What is cross-site scripting (XSS)?

Topic: Requests, storage, and security

SHORT ANSWER

Untrusted content executes as script in a site's context. Use safe text rendering and appropriate sanitization for allowed HTML.

145

Why can inserting user input with innerHTML be dangerous?

Topic: Requests, storage, and security

SHORT ANSWER

It parses input as markup and can enable XSS. Use textContent for plain text.

146

What is cross-site request forgery (CSRF)?

Topic: Requests, storage, and security

SHORT ANSWER

A malicious site causes unwanted authenticated requests. Mitigations include appropriate SameSite cookies, CSRF tokens, and origin validation.

147

What do the HttpOnly, Secure, and SameSite cookie attributes do?

Topic: Requests, storage, and security

SHORT ANSWER

They restrict script access, transport to HTTPS, and cross-site sending, respectively.

148

Why can you not safely hide a secret API key in frontend JavaScript?

Topic: Requests, storage, and security

SHORT ANSWER

Users can inspect downloaded code and requests. Keep privileged secrets on a trusted server.

149

What causes race conditions in search-as-you-type requests?

Topic: Requests, storage, and security

SHORT ANSWER

Older responses may arrive later and overwrite newer results; cancel stale requests or check a request identifier.

150

How do you handle intermittent request failures?

Topic: Requests, storage, and security

SHORT ANSWER

Use bounded retries with backoff for suitable operations; avoid blindly repeating non-idempotent actions.

151

What are JavaScript modules?

Topic: Modules, performance, and testing

SHORT ANSWER

Files with explicit imports and exports, their own scope, and strict-mode behavior.

152

What is the difference between named and default exports?

Topic: Modules, performance, and testing

SHORT ANSWER

Named exports are imported by exported name; a default export can be given any local import name.

153

How do static import and dynamic import() differ?

Topic: Modules, performance, and testing

SHORT ANSWER

Static imports declare dependencies upfront; import() loads a module on demand and returns a promise.

154

How do ES modules and CommonJS differ?

Topic: Modules, performance, and testing

SHORT ANSWER

ESM uses import/export and live bindings; CommonJS uses require/module.exports and typically loads synchronously.

155

What is the difference between a transpiler and a polyfill?

Topic: Modules, performance, and testing

SHORT ANSWER

A transpiler rewrites syntax; a polyfill supplies a missing runtime API.

156

What are bundling, tree shaking, and code splitting?

Topic: Modules, performance, and testing

SHORT ANSWER

Bundling combines modules; tree shaking removes unused code; code splitting separates code for selective loading.

157

What does strict mode change?

Topic: Modules, performance, and testing

SHORT ANSWER

It rejects some previously silent mistakes, forbids accidental globals, and changes plain-call this to undefined.

158

How does garbage collection work at a high level?

Topic: Modules, performance, and testing

SHORT ANSWER

The engine reclaims memory that is no longer reachable; the exact timing is not guaranteed.

159

What commonly causes memory leaks in JavaScript applications?

Topic: Modules, performance, and testing

SHORT ANSWER

Unwanted reachable data, such as retained listeners, timers, detached DOM nodes, or unbounded caches.

160

How would you investigate a slow JavaScript application?

Topic: Modules, performance, and testing

SHORT ANSWER

Reproduce it, profile the bottleneck, measure a targeted change, and check for regressions.

161

What is layout thrashing, and how can you reduce it?

Topic: Modules, performance, and testing

SHORT ANSWER

Repeated DOM writes followed by layout reads can force extra layout; batch reads and writes.

162

How does browser JavaScript differ from Node.js?

Topic: Modules, performance, and testing

SHORT ANSWER

They share the language but expose different host APIs: browsers provide the DOM; Node provides server and filesystem APIs.

163

What is the difference between unit, integration, and end-to-end tests?

Topic: Modules, performance, and testing

SHORT ANSWER

Unit tests check small units; integration tests check interactions; end-to-end tests check complete user flows.

164

How do you test asynchronous JavaScript?

Topic: Modules, performance, and testing

SHORT ANSWER

Return or await the operation, assert outcomes and failures, and control timers or external dependencies when needed.

165

How would you debug an unfamiliar JavaScript bug?

Topic: Modules, performance, and testing

SHORT ANSWER

Reproduce it, reduce the case, inspect state and stack traces, test a hypothesis, and verify the fix.

166

How would you remove duplicate primitive values from an array?

Topic: Common coding exercises and output questions

SHORT ANSWER

Use [...new Set(values)]; decide separately how object duplicates should be identified.

167

How would you count occurrences of each value in an array?

Topic: Common coding exercises and output questions

SHORT ANSWER

Accumulate counts in a Map, incrementing the count for each value.

168

How would you check whether a string is a palindrome?

Topic: Common coding exercises and output questions

SHORT ANSWER

Define normalization rules, then compare characters from both ends or compare with a reversed copy.

169

How would you check whether two strings are anagrams?

Topic: Common coding exercises and output questions

SHORT ANSWER

Normalize as required and compare character frequencies, or sort and compare their characters.

170

How would you flatten a nested array?

Topic: Common coding exercises and output questions

SHORT ANSWER

Use flat(depth), or recursively visit nested arrays. Choose whether all nesting should be flattened.

171

How would you implement debounce?

Topic: Common coding exercises and output questions

SHORT ANSWER

Keep a timer in a closure; clear it on each call, then schedule the callback with the latest arguments and receiver.

172

How would you implement throttle?

Topic: Common coding exercises and output questions

SHORT ANSWER

Track the last execution or a pending timer; define whether leading and trailing calls should run.

173

How would you implement a counter with private state?

Topic: Common coding exercises and output questions

SHORT ANSWER

Return a function that closes over a local count and increments it on each call.

174

How would you group an array of objects by a property?

Topic: Common coding exercises and output questions

SHORT ANSWER

Accumulate arrays in a Map keyed by that property; append each object to its group.

175

What does this log? console.log('5' + 2, '5' - 2);

Topic: Common coding exercises and output questions

SHORT ANSWER

'52' and 3. Addition concatenates when a string operand is involved; subtraction converts to numbers.

176

What does this log? console.log([] === [], NaN === NaN);

Topic: Common coding exercises and output questions

SHORT ANSWER

false, false. The arrays have different identities; NaN is not strictly equal to itself.

177

What does this log? let a = { n: 1 }; let b = a; b.n = 2; console.log(a.n);

Topic: Common coding exercises and output questions

SHORT ANSWER

2. Both variables refer to the same object.

178

What does this log? console.log(x); var x = 7;

Topic: Common coding exercises and output questions

SHORT ANSWER

undefined. The var binding exists before its initializer runs.

179

What happens here? console.log(x); let x = 7;

Topic: Common coding exercises and output questions

SHORT ANSWER

A ReferenceError: x is accessed during its temporal dead zone.

180

In a browser, what is the output order? console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');

Topic: Common coding exercises and output questions

SHORT ANSWER

A, D, C, B: synchronous logs, then the promise microtask, then the timer task.