Questions 121–140 of 200 · 0 of 20 on this page marked learned
121.javascript-0121Easyfresher
How do you write binary search correctly, including finding the first occurrence and the insertion position?
Binary search repeatedly halves a sorted range by comparing the middle element with the target, so it takes O(log n) time. Keep clear invariants for the left and right bounds, compute the middle without overflow-style mistakes, and use the lower-bound form to find the first occurrence or insertion index. It only works on sorted data.
Full answer
Binary search finds a value in a sorted array in O(log n) steps. At each step, look at the middle element. If it equals the target, you are done. If the target is smaller, discard the right half. If it is larger, discard the left half.
Most bugs come from unclear bounds. Pick one convention and keep it. A safe one is the half-open range [left, right): start with left = 0 and right = array.length, loop while (left < right), compute mid = left + Math.floor((right - left) / 2), then move left = mid + 1 or right = mid. In JavaScript, integers do not overflow the way they do in other languages, so (left + right) / 2 is safe, but you still need Math.floor, and the left + (right - left) / 2 habit is good practice.
The most useful version is the lower bound: the first index whose value is not less than the target. The loop keeps the invariant that everything before left is smaller than the target and everything from right on is not smaller. When the loop ends, left is the first occurrence if it exists, or the position where the target should be inserted to keep the array sorted. The upper bound is the same with <=. The count of a value is upper - lower.
Binary search is also a technique for answers, not only for arrays: find the smallest value of a number for which a condition is true, as long as the condition is monotonic (false, false, true, true). Examples are integer square root and the smallest capacity that ships packages in D days.
Pitfalls: unsorted input, a comparator that does not match the sort order, an infinite loop caused by left = mid without progress, and sorting strings with the default sort when numbers are meant. Note that Array.prototype.indexOf is O(n), and includes too, so for repeated lookups on large data, sort once and use binary search, or use a Set.
javascript
function lowerBound(sorted, target) {
let left = 0;
let right = sorted.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (sorted[mid] < target) left = mid + 1;
else right = mid;
}
return left;
}
function upperBound(sorted, target) {
let left = 0;
let right = sorted.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (sorted[mid] <= target) left = mid + 1;
else right = mid;
}
return left;
}
function binarySearch(sorted, target) {
const index = lowerBound(sorted, target);
return index < sorted.length && sorted[index] === target ? index : -1;
}
function integerSqrt(n) {
let left = 0;
let right = n + 1; // first x with x * x > n is in [0, n + 1]
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (mid * mid <= n) left = mid + 1;
else right = mid;
}
return left - 1;
}
const data = [1, 3, 3, 3, 5, 8, 13];
console.log(binarySearch(data, 8), binarySearch(data, 4), binarySearch([], 1));
console.log('first 3 at', lowerBound(data, 3), 'count of 3:', upperBound(data, 3) - lowerBound(data, 3));
console.log('insert 4 at', lowerBound(data, 4), 'insert 0 at', lowerBound(data, 0), 'insert 99 at', lowerBound(data, 99));
console.log([0, 1, 15, 16, 17, 99, 100].map((n) => integerSqrt(n)));
// check against the built-in on many cases
let ok = true;
for (let length = 0; length < 30; length++) {
const array = Array.from({ length }, (_, i) => Math.floor(i / 2));
for (let target = -1; target <= length; target++) {
if (binarySearch(array, target) !== -1 !== array.includes(target)) ok = false;
if (lowerBound(array, target) !== array.findIndex((x) => x >= target) && array.some((x) => x >= target)) ok = false;
}
}
console.log('agrees with includes and findIndex:', ok);
console.log([10, 9, 1].sort(), [10, 9, 1].sort((a, b) => a - b));
Run with Node.js v24.22.1 as js-121.js; two runs gave identical output.
Output:
5 -1 -1
first 3 at 1 count of 3: 3
insert 4 at 4 insert 0 at 0 insert 99 at 7
[
0, 1, 3, 4,
4, 9, 10
]
agrees with includes and findIndex: true
[ 1, 10, 9 ] [ 1, 9, 10 ]
Key points
Halve a sorted range each step for O(log n); input must be sorted.
Use one clear bounds convention, such as half-open [left, right).
Lower bound gives the first occurrence or insertion index; upper bound minus lower bound gives the count.
It also works on monotonic conditions, such as integer square root.
Avoid infinite loops: always move left to mid plus 1 or right to mid.
Common mistakes
Running binary search on unsorted data or on numbers sorted as strings.
Mixing bound conventions, which gives off-by-one errors and infinite loops.
Returning the first match found, when the first occurrence is needed.
Using indexOf in a loop on large arrays instead of sorting once.
Follow-ups
How would you search in a rotated sorted array?
How does the lower bound help to insert into a sorted array?
How would you apply binary search to find the smallest valid value of a condition?
Tips
State the bounds convention and the loop invariant before coding.
Use lower bound as the base for first occurrence, insertion, and count.
Mention that it also works on monotonic conditions.
122.javascript-0122Easyfresher
How do you check whether a string of brackets is balanced, and how do you report where it goes wrong?
Use a stack: push each opening bracket, and for each closing bracket pop and check that it matches the expected pair. The string is balanced if every closing bracket matched and the stack is empty at the end. This is O(n) time and O(n) space, and it can report the position of the first error.
Full answer
A string such as {[()]} is balanced when every opening bracket is closed by the same type, in the right order. Counting brackets is not enough: ([)] has equal counts but is wrong. The nested structure needs a stack, which gives last in, first out order.
Algorithm:
Create a Map from each closing bracket to its opening bracket: ) to (, ] to [, } to {.
For each character: if it is an opening bracket, push it (with its position if you want error reports). If it is a closing bracket, pop the stack. If the stack was empty or the popped value is not the expected opening bracket, the string is invalid.
Ignore other characters if the input can contain normal text, which is the case for code.
After the loop, the string is balanced only if the stack is empty. Otherwise some brackets were never closed.
Complexity is O(n) time and O(n) space in the worst case, when the input is all opening brackets. Quick checks help: an odd length (when the input has only brackets) can never be balanced.
Using a plain JavaScript array as a stack is idiomatic: push and pop are O(1).
Follow-ups that are common: return the index of the first error (store indexes on the stack), find the minimum number of removals to make a string balanced (a variation with a counter), and extend the rule to HTML tags or to quotes that must not be counted inside strings. For a single bracket type, a counter is enough, and it must never go below zero.
This is the same idea that parsers use to check nesting, and it is a good bridge to the call stack and recursion.
javascript
const PAIRS = new Map([[')', '('], [']', '['], ['}', '{']]);
const OPENERS = new Set(PAIRS.values());
function checkBrackets(text) {
const stack = [];
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (OPENERS.has(ch)) {
stack.push({ ch, i });
} else if (PAIRS.has(ch)) {
const top = stack.pop();
if (!top) return { valid: false, reason: `unexpected ${ch} at ${i}` };
if (top.ch !== PAIRS.get(ch)) return { valid: false, reason: `${ch} at ${i} does not match ${top.ch} at ${top.i}` };
}
}
if (stack.length > 0) {
const open = stack[stack.length - 1];
return { valid: false, reason: `${open.ch} at ${open.i} is never closed` };
}
return { valid: true, reason: 'balanced' };
}
const isBalanced = (text) => checkBrackets(text).valid;
for (const sample of ['{[()]}', '([)]', '((', '())', '', 'a(b[c]{d})e', ']']) {
console.log(JSON.stringify(sample).padEnd(16), checkBrackets(sample));
}
function minAddsForParentheses(text) {
let open = 0;
let adds = 0;
for (const ch of text) {
if (ch === '(') open++;
else if (ch === ')') open > 0 ? open-- : adds++;
}
return adds + open;
}
console.log(isBalanced('{[()]}'), isBalanced('(]'), minAddsForParentheses('())('), minAddsForParentheses('((('));
Run with Node.js v24.22.1 as js-122.js; two runs gave identical output.
Output:
"{[()]}" { valid: true, reason: 'balanced' }
"([)]" { valid: false, reason: ') at 2 does not match [ at 1' }
"((" { valid: false, reason: '( at 1 is never closed' }
"())" { valid: false, reason: 'unexpected ) at 2' }
"" { valid: true, reason: 'balanced' }
"a(b[c]{d})e" { valid: true, reason: 'balanced' }
"]" { valid: false, reason: 'unexpected ] at 0' }
true false 2 3
Key points
Push opening brackets; on a closing bracket pop and compare with the expected pair.
Balanced means no mismatch and an empty stack at the end.
Counting alone fails for ([)] because order matters.
O(n) time, O(n) space; an array with push and pop works as the stack.
Store positions on the stack to report the first error; one bracket type needs only a counter.
Common mistakes
Comparing counts of brackets instead of using a stack.
Forgetting the empty stack check at the end.
Popping from an empty stack and not handling it.
Treating brackets inside string literals as real brackets when the input is code.
Follow-ups
How would you find the longest valid parentheses substring?
How would the solution change for HTML tags?
How is this related to the call stack?
Tips
Show ([)] as the case where counting fails.
Return a reason and position, since many interviewers ask for it.
Check the stack at the end.
123.javascript-0123Mediummid
How do you write higher-order function utilities such as once, before, after, negate, and unary?
Each utility is a function that takes a function and returns a new function that remembers state in a closure. once runs the original a single time and caches the result, before and after limit or delay calls, negate flips a predicate, and unary passes only the first argument, which fixes the classic map and parseInt bug. Preserve this and arguments with a regular function and apply.
Full answer
Higher-order functions take or return functions. Utility wrappers show closures at work, because the wrapper keeps private state (a counter or a result) between calls.
once(fn): the first call runs fn and stores the result. Later calls return the stored result without calling fn. Keep a called flag, and keep the result, so that a function that returns undefined is not run again. Set the reference to fn to null after the first call so the original can be garbage collected.
before(n, fn): allow the first n - 1 calls to run fn, then keep returning the last result. after(n, fn): ignore the first n - 1 calls, and run fn from call number n onward. A common use of after is to run a callback once all of n tasks have reported in.
negate(predicate): returns a function that gives the opposite boolean, so items.filter(negate(isEven)) reads well.
unary(fn): calls fn with only the first argument. This fixes ['1', '2', '3'].map(parseInt), which returns [1, NaN, NaN]. map calls the function with the value, the index, and the array, and parseInt reads the index as the radix. The same trap affects any function with optional second parameters.
Implementation rules for all of them: return a regular function and use fn.apply(this, args) so that methods keep their this; copy extra properties only if needed; and do not share state between separate wrappers, which a closure per call of the utility gives you for free. If the wrapped function can throw, decide whether once should cache the failure or run again. The usual choice is that a failed first call does not count, but state it clearly.
These utilities are also the building blocks of memoize, debounce, and retry wrappers.
javascript
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
result = fn.apply(this, args);
called = true;
fn = null;
}
return result;
};
}
const before = (n, fn) => {
let calls = 0;
let result;
return function (...args) {
if (++calls < n) result = fn.apply(this, args);
return result;
};
};
const after = (n, fn) => {
let calls = 0;
return function (...args) {
if (++calls >= n) return fn.apply(this, args);
};
};
const negate = (predicate) => function (...args) {
return !predicate.apply(this, args);
};
const unary = (fn) => function (first) {
return fn.call(this, first);
};
let initialized = 0;
const init = once(() => ++initialized);
console.log(init(), init(), init(), 'run count:', initialized);
const returnsNothing = once(() => { initialized++; });
returnsNothing();
returnsNothing();
console.log('function returning undefined ran once:', initialized === 2);
const log = [];
const firstTwo = before(3, (x) => { log.push('before ' + x); return x; });
console.log(firstTwo('a'), firstTwo('b'), firstTwo('c'), firstTwo('d'), log);
const done = after(3, () => 'all three reported');
console.log(done(), done(), done(), done());
const isEven = (n) => n % 2 === 0;
console.log([1, 2, 3, 4, 5].filter(negate(isEven)));
console.log(['1', '2', '3'].map(parseInt), ['1', '2', '3'].map(unary(parseInt)));
const user = { name: 'Asha', greet: once(function () { return 'hi ' + this.name; }) };
console.log(user.greet(), user.greet());
Run with Node.js v24.22.1 as js-123.js; two runs gave identical output.
Output:
1 1 1 run count: 1
function returning undefined ran once: true
a b b b [ 'before a', 'before b' ]
undefined undefined all three reported all three reported
[ 1, 3, 5 ]
[ 1, NaN, NaN ] [ 1, 2, 3 ]
hi Asha hi Asha
Key points
Wrappers take a function, return a function, and keep state in a closure.
once caches the result with a flag, not by checking for undefined.
before limits and after delays the calls of the original; after is useful to wait for n results.
negate flips a predicate; unary fixes map with parseInt.
Use a regular function and apply to preserve this; decide how errors count for once.
Common mistakes
Using an arrow function wrapper and losing this for methods.
Detecting the first call with result being undefined, so functions that return undefined run again.
Forgetting that map passes index and array to the callback.
Sharing one counter across wrappers instead of one closure each.
Follow-ups
How would you write once so that a failed first call can be retried?
What other callbacks have the map and parseInt problem?
How would you build debounce from these ideas?
Tips
Explain that the closure holds the state.
Use map with parseInt as the motivating example for unary.
Mention this and arguments preservation.
124.javascript-0124Easyfresher
How do you solve FizzBuzz, reverse a string, count vowels, and find the largest number in an array, and what do interviewers look for?
These warm-up questions test loops, conditions, the modulo operator, string and array methods, and clear thinking about edge cases. For FizzBuzz, check the combined multiple of 15 first, or build the word from parts. For strings, remember that they are immutable and spread by code point. For the largest number, use a loop or Math.max with spread, and handle empty arrays.
Full answer
Warm-up problems are short, and interviewers watch how you work: do you ask about the input, handle edge cases, and write readable code?
FizzBuzz: print numbers from 1 to n, but "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for both. The classic mistake is to test the multiple of 3 first, so 15 prints "Fizz". Either test i % 15 === 0 first, or build the output: start with an empty string, add "Fizz" if divisible by 3, add "Buzz" if divisible by 5, and use the number if the string is still empty. The second form extends cleanly to more rules.
Reverse a string: strings are immutable, so produce a new one. [...text].reverse().join('') works for most text, because spread walks code points, while split('') splits surrogate pairs in emoji and breaks them. A loop that builds from the end works too. Mention that perfect handling of combined characters needs Intl.Segmenter.
Count vowels: lowercase the text, then count matches against a Set of vowels, or use match(/[aeiou]/g), which returns null when there is no match, so use ?.length ?? 0.
Largest number: Math.max(...numbers) is short but throws a RangeError for very large arrays (the spread passes every element as an argument), and returns -Infinity for an empty array. A reduce or a loop is safe for any size. Decide what to return for empty input: undefined, null, or an error.
What interviewers look for: correct edge cases (empty input, negative numbers, one element), readable names, no unneeded work, and the ability to explain the time complexity, which here is O(n) for each problem.
javascript
function fizzBuzz(n) {
const out = [];
for (let i = 1; i <= n; i++) {
let word = '';
if (i % 3 === 0) word += 'Fizz';
if (i % 5 === 0) word += 'Buzz';
out.push(word || String(i));
}
return out;
}
const reverseString = (text) => [...text].reverse().join('');
function countVowels(text) {
const vowels = new Set('aeiou');
let count = 0;
for (const ch of text.toLowerCase()) if (vowels.has(ch)) count++;
return count;
}
const countVowelsRegex = (text) => text.match(/[aeiou]/gi)?.length ?? 0;
function largest(numbers) {
if (numbers.length === 0) return undefined;
let best = numbers[0];
for (const n of numbers) if (n > best) best = n;
return best;
}
console.log(fizzBuzz(15).join(' '));
console.log(reverseString('hello'), JSON.stringify(reverseString('')), reverseString('a\u{1F600}b') === 'b\u{1F600}a');
console.log(countVowels('Interview Questions'), countVowelsRegex('Interview Questions'), countVowelsRegex('xyz'));
console.log(largest([3, -1, 7, 7, 2]), largest([-5, -2, -9]), largest([]), Math.max(), Math.max(...[]));
try {
Math.max(...new Array(200000).fill(1));
console.log('spread of 200000 items worked in this engine');
} catch (error) {
console.log('Math.max with a huge spread:', error.name);
}
console.log(largest(new Array(200000).fill(1)));
Run with Node.js v24.22.1 as js-124.js; two runs gave identical output.
Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
olleh "" true
8 8 0
7 -2 undefined -Infinity -Infinity
Math.max with a huge spread: RangeError
1
Key points
FizzBuzz: test the multiple of 15 first, or build the word from parts.
Strings are immutable; reverse with spread and join, not split with an empty string, for emoji.
match returns null when nothing matches; guard it.
Math.max with spread fails for huge arrays and gives -Infinity for empty ones; use a loop or reduce.
Show edge cases and complexity; all four are O(n).
Common mistakes
Testing for multiples of 3 before testing for multiples of 15.
Reversing with split('') and breaking emoji.
Calling .length on the null result of match.
Using Math.max with spread on very large arrays, or on an empty array without a plan.
Follow-ups
How would you add a rule such as 7 to FizzBuzz without a long if chain?
How would you reverse the words of a sentence but not the letters?
Why does Math.max of nothing return minus Infinity?
Tips
Mention edge cases before you write code.
Choose clear names and a short, readable solution.
State the complexity even for easy problems.
125.javascript-0125Mediummid
How do you update the DOM in an accessible way, using aria-expanded, live regions, and focus management?
Use native elements (button, label, input) first, since they bring keyboard support and roles for free. When you build custom behavior, keep ARIA state in sync with the visual state: aria-expanded and aria-controls on a disclosure button, aria-invalid and aria-describedby on invalid fields, a live region to announce changes, and move focus deliberately after content changes. Test with the keyboard and a screen reader.
Full answer
Accessible DOM scripting means that people who use a keyboard, a screen reader, or voice control can do everything a mouse user can do. The first rule of ARIA is to use a native element when one exists. A button is focusable, activates with Enter and Space, and has the role button. A div with a click handler has none of that.
Disclosure (show and hide): use a button with aria-expanded="true" or "false" and aria-controls pointing to the id of the panel. When toggled, update the attribute and show or hide the panel with the hidden attribute (which also removes it from the accessibility tree). Do not hide with opacity alone. Update the attribute in the same place as the visual change, so they cannot drift apart.
Announcing changes: content that changes without a page load is invisible to a screen reader unless announced. Use a live region: an element with role="status" (polite) or role="alert" (assertive) that exists in the page before you change its text. Put short messages in it, such as "3 results found" or "Item added". Do not move focus just to announce.
Forms: on an invalid field, set aria-invalid="true", connect the error text with aria-describedby, and put focus on the first invalid field after a failed submit. Use a label linked with for, not only a placeholder.
Focus management: when content opens (a dialog) move focus into it and return it to the trigger on close. The native dialog element with showModal() does this, plus a focus trap and the Escape key. When you remove the focused element, such as a deleted list item, move focus to a sensible neighbor, otherwise it falls back to the page start.
Also keep a visible focus style, never remove outlines without a replacement, and test by tabbing through the page. Automated tools catch only part of the problems, so a manual pass is needed.
javascript
document.body.innerHTML = `
<button id="toggle" aria-expanded="false" aria-controls="details">Show details</button>
<div id="details" hidden>More information</div>
<div id="status" role="status"></div>
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" type="email" aria-describedby="email-error">
<div id="email-error"></div>
<button type="submit">Sign up</button>
</form>`;
const $ = (selector) => document.querySelector(selector);
// 1. Disclosure: keep aria-expanded and hidden in sync in one function
function setExpanded(button, panel, expanded) {
button.setAttribute('aria-expanded', String(expanded));
panel.hidden = !expanded;
button.textContent = expanded ? 'Hide details' : 'Show details';
}
$('#toggle').addEventListener('click', () => {
const open = $('#toggle').getAttribute('aria-expanded') === 'true';
setExpanded($('#toggle'), $('#details'), !open);
$('#status').textContent = open ? 'Details hidden' : 'Details shown';
});
const state = () => ({
expanded: $('#toggle').getAttribute('aria-expanded'),
panelHidden: $('#details').hidden,
label: $('#toggle').textContent,
announced: $('#status').textContent,
});
console.log('initial', state());
$('#toggle').click();
console.log('after click', state());
$('#toggle').click();
console.log('after second click', state());
// 2. Form errors: aria-invalid, aria-describedby text, focus on the first invalid field
$('#signup').addEventListener('submit', (event) => {
event.preventDefault();
const input = $('#email');
const valid = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(input.value);
if (valid) input.removeAttribute('aria-invalid');
else input.setAttribute('aria-invalid', 'true');
$('#email-error').textContent = valid ? '' : 'Enter an email address such as name@example.com';
if (!valid) input.focus();
$('#status').textContent = valid ? 'Signed up' : 'The form has 1 error';
});
$('#signup').requestSubmit();
console.log('invalid:', $('#email').getAttribute('aria-invalid'), '| focused:', document.activeElement.id, '|', $('#email-error').textContent);
$('#email').value = 'asha@example.com';
$('#signup').requestSubmit();
console.log('valid:', $('#email').hasAttribute('aria-invalid'), '|', JSON.stringify($('#email-error').textContent), '|', $('#status').textContent);
// 3. Removing the focused element: move focus to a sensible place
document.body.insertAdjacentHTML('beforeend', '<ul id="list"><li><button>Delete A</button></li><li><button>Delete B</button></li></ul>');
const [first, second] = document.querySelectorAll('#list button');
first.focus();
console.log('before delete, focus on:', document.activeElement.textContent);
first.closest('li').remove();
console.log('after remove, focus on:', document.activeElement === document.body ? 'body (lost)' : document.activeElement.textContent);
second.focus();
console.log('after moving focus to the next item:', document.activeElement.textContent);
Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output.
Output:
initial {
expanded: 'false',
panelHidden: true,
label: 'Show details',
announced: ''
}
after click {
expanded: 'true',
panelHidden: false,
label: 'Hide details',
announced: 'Details shown'
}
after second click {
expanded: 'false',
panelHidden: true,
label: 'Show details',
announced: 'Details hidden'
}
invalid: true | focused: email | Enter an email address such as name@example.com
valid: false | "" | Signed up
before delete, focus on: Delete A
after remove, focus on: body (lost)
after moving focus to the next item: Delete B
Key points
Prefer native elements; they give role, focus, and keyboard behavior for free.
Disclosure: button with aria-expanded and aria-controls, panel shown with the hidden attribute.
Announce changes with an existing live region (status or alert), without moving focus.
Invalid fields: aria-invalid, aria-describedby for the message, focus on the first error.
Move focus into opened content, return it on close, and never lose it when removing elements.
Common mistakes
Using a div with a click handler instead of a button.
Changing the visual state and forgetting to update aria-expanded.
Creating the live region at the same time as the message, so it is not announced.
Removing the focused element and leaving focus on the page body.
Follow-ups
What is the difference between role="status" and role="alert"?
How does the native dialog element help with focus?
Which parts of accessibility testing can be automated, and which cannot?
Tips
Start with native elements and say why.
Mention keeping ARIA state in sync in one function.
Describe focus handling for open, close, and delete actions.
126.javascript-0126Easyfresher
How do NaN, -0, and Object.is behave in JavaScript, and why does NaN not equal itself?
NaN means "not a number" and by the IEEE 754 standard it is not equal to anything, including itself, so use Number.isNaN or Object.is to test for it. JavaScript also has a signed zero: -0 equals 0 with ===, but Object.is tells them apart, and 1 divided by -0 is -Infinity. Object.is uses SameValue, while Map, Set, and includes use SameValueZero, which treats NaN as equal to NaN and -0 as equal to 0.
Full answer
NaN is the result of an invalid numeric operation, such as 0 / 0, Math.sqrt(-1), or Number('abc'). Under the IEEE 754 floating point standard, a NaN is unordered, so every comparison with it is false, including NaN === NaN. Its type is still 'number'.
Testing for NaN: the global isNaN(value) first converts the value to a number, so isNaN('abc') is true, which is misleading. Number.isNaN(value) returns true only for the actual NaN value and does no conversion. Object.is(value, NaN) also works. Prefer Number.isNaN.
Negative zero: floating point numbers have a sign bit, so -0 exists. It appears from -0 literals, 0 * -1, and Math.round(-0.4). The strict equality operator treats 0 === -0 as true, and String(-0) is '0', so it is easy to miss. It matters in 1 / -0, which is -Infinity, in Math.sign, Math.atan2, and in rounding of small negative values. Object.is(0, -0) is false.
Object.is(a, b) uses the SameValue algorithm: like ===, except that NaN equals NaN and +0 differs from -0. React uses it to compare state values.
There is a third rule, SameValueZero, used by Map keys, Set values, and Array.prototype.includes: NaN equals NaN, and +0 equals -0. But indexOf and findIndex with a value use ===, so [NaN].indexOf(NaN) is -1, while [NaN].includes(NaN) is true.
Other number edge cases that interviews cover: typeof NaN, Number('') is 0, Number(null) is 0, Number(undefined) is NaN, parseInt('12px') is 12 while Number('12px') is NaN, Math.min() is Infinity, Math.max() is -Infinity, and Number.isInteger(5.0) is true.
Run with Node.js v24.22.1 as js-126.js; two runs gave identical output.
Output:
false false number true true
true false false false
NaN NaN NaN 12 NaN
true false true 0 0
Infinity -Infinity -0 -0 true
0 [0] [ -0 ] 0 true
-1 true true 0
2 [ NaN, 0 ]
nan key zero
0 0 0 NaN 1 0 5 NaN
Infinity -Infinity true false false
[ false, true, false ] [ false, false, false ]
Key points
NaN is not equal to anything, including itself; its typeof is number.
Use Number.isNaN, not the global isNaN, which converts first.
-0 exists; === treats it as equal to 0, Object.is does not, and 1 divided by -0 is -Infinity.
Object.is is SameValue; Map, Set, and includes use SameValueZero; indexOf uses strict equality.
Know the conversions: Number of empty string and null is 0, of undefined is NaN.
Common mistakes
Testing for NaN with x === NaN, which is always false.
Using the global isNaN on strings and getting true for any non-numeric text.
Using indexOf to look for NaN.
Forgetting that JSON and string conversion hide the sign of zero.
Follow-ups
What is the difference between SameValue and SameValueZero, and where is each used?
Why does Math.round of a small negative number give -0?
How would you detect -0 without Object.is?
Tips
Give the one-line reason: NaN is unordered by the floating point standard.
Recommend Number.isNaN and explain what the global isNaN does wrong.
Name the three equality algorithms and where each appears.
127.javascript-0127Easyfresher
What are the core ideas of functional programming in JavaScript, such as pure functions, immutability, and higher-order functions?
Functional programming builds programs from small pure functions, which return the same output for the same input and cause no side effects, on immutable data, combined with higher-order functions and composition. It makes code easier to test and reason about. JavaScript supports it because functions are first-class values, though it does not enforce purity or immutability.
Full answer
Functional programming (FP) is a style, not a library. JavaScript is multi-paradigm, so you can mix it with object-oriented code.
Pure functions: the output depends only on the arguments, and the function changes nothing outside itself. Reading the current time, random numbers, a global variable, or writing to the DOM, a file, or the console makes a function impure. Pure functions are easy to test (no setup), safe to cache (memoize), and safe to run in any order. An expression that can be replaced by its value without changing the program has referential transparency.
Side effects are still needed, because programs must read input and write output. The FP approach is to keep them at the edges and keep the core logic pure.
Immutability: do not change data in place. Create new values: spread for objects and arrays, map, filter, and toSorted instead of push and sort. This avoids bugs where a shared object is changed by distant code, and it makes change detection cheap, because a new reference means a change (the base of React state updates). Object.freeze can enforce it shallowly.
First-class and higher-order functions: functions can be stored in variables, passed to other functions, and returned from them. map, filter, and reduce are higher-order functions that replace loops with intent.
Composition: build bigger behavior by chaining small functions, with pipe(f, g, h)(x) meaning h(g(f(x))). Currying and partial application make functions easier to compose.
Declarative style: say what you want (users.filter(isActive).map(getName)), not how to loop.
Trade-offs: creating new objects costs memory and time (usually small), deep pipelines can be harder to debug, and too much cleverness reduces readability. In practice, use FP where it helps: pure helpers, immutable updates, and array pipelines.
javascript
// impure: reads and changes outside state
let total = 0;
function addToTotalImpure(n) {
total += n;
return total;
}
console.log(addToTotalImpure(5), addToTotalImpure(5));
// pure: depends only on its arguments
const add = (a, b) => a + b;
console.log(add(5, 5), add(5, 5));
// mutation versus a new value
const cart = Object.freeze([{ name: 'pen', price: 2 }, { name: 'book', price: 12 }]);
const withItem = [...cart, { name: 'bag', price: 30 }];
console.log(cart.length, withItem.length, cart === withItem);
try {
cart.push({ name: 'x', price: 1 });
} catch (error) {
console.log('frozen array push:', error.name);
}
// higher-order functions and pipelines
const users = [
{ name: 'Asha', active: true, age: 31 },
{ name: 'Ben', active: false, age: 25 },
{ name: 'Chen', active: true, age: 42 },
];
const isActive = (user) => user.active;
const getName = (user) => user.name;
console.log(users.filter(isActive).map(getName));
console.log(users.reduce((sum, user) => sum + user.age, 0) / users.length);
// composition
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const slugify = pipe(
(text) => text.trim(),
(text) => text.toLowerCase(),
(text) => text.replace(/[^a-z0-9]+/g, '-'),
(text) => text.replace(/^-|-$/g, ''),
);
console.log(slugify(' Hello, Functional World! '));
// immutable update of a nested object
const state = { user: { name: 'Asha', tags: ['a'] }, count: 1 };
const next = { ...state, user: { ...state.user, tags: [...state.user.tags, 'b'] } };
console.log(state.user.tags, next.user.tags, state.count === next.count, state.user === next.user);
// sorting without changing the original
const scores = [30, 5, 100];
console.log(scores.toSorted((a, b) => a - b), scores);
Run with Node.js v24.22.1 as js-127.js; two runs gave identical output.
Output:
5 10
10 10
2 3 false
frozen array push: TypeError
[ 'Asha', 'Chen' ]
32.666666666666664
hello-functional-world
[ 'a' ] [ 'a', 'b' ] true false
[ 5, 30, 100 ] [ 30, 5, 100 ]
Key points
Pure function: same input gives same output, with no side effects; easy to test and cache.
Keep side effects at the edges and the core logic pure.
Immutability: create new values with spread, map, filter, and toSorted instead of changing data.
Higher-order functions and composition build behavior from small pieces.
JavaScript allows FP but does not enforce it; balance purity with readability.
Common mistakes
Calling a function pure while it reads the date, random values, or global state.
Believing that const or Object.freeze make nested data deeply immutable.
Mutating inputs with sort, reverse, or splice inside "pure" functions.
Chaining very long pipelines with no names, which hurts readability and debugging.
Follow-ups
Why does immutability make change detection cheap in UI libraries?
What is referential transparency, and how does it help with memoization?
Where would you still use mutation for performance, and how would you contain it?
Tips
Define pure function with an example and a counterexample.
Say that side effects are pushed to the edges of the program.
Mention the trade-offs, so the answer does not sound like a sales pitch.
128.javascript-0128Easyfresher
How do Node.js and the browser differ as JavaScript environments, in globals, modules, and available APIs?
Both run the same language, but the global object and the APIs around it differ. Browsers provide window, document, and Web APIs for the page, while Node.js provides process, Buffer, file system, and network modules, and has no DOM. Modern Node.js also includes many web standard APIs such as fetch, URL, and AbortController. Use globalThis and feature detection when code must run in both.
Full answer
JavaScript the language (ECMAScript) is the same in both. What differs is the host environment: the global object, the built-in APIs, the module system, and the security model.
Browser: the global object is window (and self in workers). It provides document and the DOM, location, history, localStorage, fetch, XMLHttpRequest, alert, requestAnimationFrame, and many more Web APIs. Scripts run in a sandbox with same-origin rules and cannot read files freely.
Node.js: a server-side runtime. The global object is global, and globalThis works everywhere. There is no window or document. It provides process (arguments, environment variables, exit codes), Buffer, and built-in modules such as fs, path, http, crypto, and child_process. Node can read files and open sockets, so it has no sandbox by default.
Standard APIs shared today: fetch, URL, URLSearchParams, AbortController, TextEncoder, structuredClone, setTimeout, queueMicrotask, performance, and EventTarget exist in both, although small details differ. One known difference: setTimeout returns a number in browsers and a Timeout object in Node.js.
Modules: browsers use ES modules (<script type="module">). Node.js supports both CommonJS (require, module.exports, __dirname) and ES modules (import, import.meta.dirname), chosen by the file extension (.mjs or .cjs) or the type field in package.json. require and __dirname do not exist in ES module files.
Top level this: in a browser script it is window; in a Node.js CommonJS module it is module.exports; in an ES module it is undefined.
For code that must run in both, avoid assuming either side. Use globalThis, check for a feature (typeof document !== 'undefined') instead of checking the browser name, and keep environment-specific code in separate modules. This matters for server-side rendering, where code written for the browser runs once on the server.
javascript
const has = (name) => typeof globalThis[name] !== 'undefined';
console.log('browser globals present:', ['window', 'document', 'localStorage', 'alert'].map((n) => `${n}=${has(n)}`).join(' '));
console.log('node globals (typeof):', typeof process, typeof Buffer, typeof require, typeof __dirname);
console.log('require and __dirname are module wrappers, not on globalThis:', 'require' in globalThis, '__dirname' in globalThis);
console.log('shared web APIs:', ['fetch', 'URL', 'AbortController', 'structuredClone', 'TextEncoder', 'queueMicrotask', 'performance', 'EventTarget'].map((n) => `${n}=${has(n)}`).join(' '));
console.log('globalThis is global:', globalThis === global, '| window is undefined:', typeof window);
const isNode = typeof process !== 'undefined' && Boolean(process.versions?.node);
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
console.log({ isNode, isBrowser });
const timer = setTimeout(() => {}, 0);
console.log('setTimeout returns:', typeof timer, timer.constructor.name);
clearTimeout(timer);
console.log('top level this in CommonJS is module.exports:', this === module.exports);
console.log('file name helpers exist:', typeof __filename, typeof __dirname);
const { readFileSync } = require('node:fs');
console.log('node only module works:', typeof readFileSync);
// a shared function that works in both environments
function currentEnvironment() {
if (typeof document !== 'undefined') return 'browser';
if (typeof process !== 'undefined' && process.versions?.node) return 'node';
return 'unknown';
}
console.log(currentEnvironment());
Run with Node.js v24.22.1 as js-128.js; two runs gave identical output.
Output:
browser globals present: window=false document=false localStorage=false alert=false
node globals (typeof): object function function string
require and __dirname are module wrappers, not on globalThis: false false
shared web APIs: fetch=true URL=true AbortController=true structuredClone=true TextEncoder=true queueMicrotask=true performance=true EventTarget=true
globalThis is global: true | window is undefined: undefined
{ isNode: true, isBrowser: false }
setTimeout returns: object Timeout
top level this in CommonJS is module.exports: true
file name helpers exist: string string
node only module works: function
node
Key points
Same language, different host: browsers add window and the DOM; Node.js adds process, Buffer, and system modules.
Many web standard APIs are now in both: fetch, URL, AbortController, structuredClone.
Node supports CommonJS and ES modules; require and __dirname are not available in ES modules.
setTimeout returns a number in browsers and an object in Node.js; top-level this differs.
Use globalThis and feature detection; separate environment-specific code (important for server-side rendering).
Common mistakes
Using window or document in code that also runs on the server.
Using require or __dirname in an ES module.
Detecting the environment from the user agent instead of checking for the feature.
Assuming that all web APIs behave exactly the same in Node.js.
Follow-ups
How does top-level this differ in CommonJS, ES modules, and browser scripts?
Why does server-side rendering break code that reads window at import time?
How do you choose between CommonJS and ES modules in a Node.js project?
Tips
Say that the language is the same and the host APIs differ.
Mention the shared web standard APIs that reduce the gap.
Show feature detection with typeof and globalThis.
129.javascript-0129Easyfresher
What are the key fields of package.json, how do semantic version ranges work, and what is the difference between dependencies and devDependencies?
package.json describes a project: its name, version, entry points, scripts, and dependencies. Versions follow semver (major.minor.patch), where the caret allows minor and patch updates and the tilde allows only patch updates. dependencies are needed at runtime, devDependencies only for development and build, and the lockfile pins exact versions so installs are repeatable.
Full answer
package.json is the manifest of a JavaScript project. Important fields:
name and version: identify the package (required for publishing).
type: "module" makes .js files ES modules; the default is CommonJS.
main, module, and exports: entry points. exports is the modern field, and it also limits which files outsiders can import.
scripts: named commands run with npm run name. npm test and npm start have shortcuts. npx runs a package binary without a global install.
dependencies: packages needed when the code runs. devDependencies: tools needed only to build and test, such as bundlers and test runners. peerDependencies: packages the consumer must provide, common for plugins and component libraries. optionalDependencies are allowed to fail on install.
engines: the Node.js versions the package supports. files and .npmignore control what is published.
Semantic versioning has three numbers: major.minor.patch. Patch is for bug fixes, minor for backward compatible features, major for breaking changes. Ranges: ^1.2.3 accepts >=1.2.3 <2.0.0 (minor and patch updates), ~1.2.3 accepts >=1.2.3 <1.3.0 (patch updates only), and an exact 1.2.3 accepts only that. For 0.x versions the caret is stricter: ^0.2.3 means >=0.2.3 <0.3.0, because 0.x is treated as unstable.
The lockfile (package-lock.json) records the exact version of every installed package, including indirect ones. Commit it. npm install can update it within the ranges. npm ci installs exactly what the lockfile says, deletes node_modules first, and fails on a mismatch, so use it in continuous integration. Do not commit node_modules.
Security and hygiene: run npm audit, keep dependencies small, check packages before installing them, and know that install scripts run code on your machine (a supply chain risk).
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
// a minimal range checker for ^, ~ and exact versions
const parse = (v) => v.split('.').map(Number);
function satisfies(version, range) {
const v = parse(version);
const operator = /^[\^~]/.test(range) ? range[0] : '=';
const base = parse(range.replace(/^[\^~]/, ''));
const atLeast = v[0] > base[0] || (v[0] === base[0] && (v[1] > base[1] || (v[1] === base[1] && v[2] >= base[2])));
if (!atLeast) return false;
if (operator === '=') return version === range;
if (operator === '~') return v[0] === base[0] && v[1] === base[1];
if (base[0] > 0) return v[0] === base[0];
return v[0] === 0 && v[1] === base[1];
}
for (const [version, range] of [['1.9.5', '^1.2.3'], ['2.0.0', '^1.2.3'], ['1.2.9', '~1.2.3'], ['1.3.0', '~1.2.3'], ['0.2.9', '^0.2.3'], ['0.3.0', '^0.2.3'], ['1.2.2', '^1.2.3']]) {
console.log(range.padEnd(7), version.padEnd(6), satisfies(version, range));
}
// the type field decides how a .js file is loaded
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pkg-'));
fs.writeFileSync(path.join(dir, 'app.js'), "import { sep } from 'node:path';\nconsole.log('loaded as an ES module', typeof sep);\n");
const run = () => {
try {
return execFileSync(process.execPath, [path.join(dir, 'app.js')], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
} catch (error) {
return 'failed: ' + (/SyntaxError/.test(error.stderr.toString()) ? 'SyntaxError (import in a CommonJS file)' : 'other error');
}
};
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'demo', version: '1.0.0', type: 'module' }));
console.log('type module ->', run());
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'demo', version: '1.0.0', type: 'commonjs' }));
console.log('type commonjs ->', run());
fs.rmSync(dir, { recursive: true, force: true });
console.log(JSON.stringify({ scripts: { test: 'node --test', start: 'node server.js' }, engines: { node: '>=20' } }));
Run with Node.js v24.22.1 as js-129.js; two runs gave identical output.
Output:
^1.2.3 1.9.5 true
^1.2.3 2.0.0 false
~1.2.3 1.2.9 true
~1.2.3 1.3.0 false
^0.2.3 0.2.9 true
^0.2.3 0.3.0 false
^1.2.3 1.2.2 false
type module -> loaded as an ES module string
type commonjs -> failed: SyntaxError (import in a CommonJS file)
{"scripts":{"test":"node --test","start":"node server.js"},"engines":{"node":">=20"}}
dependencies are for runtime, devDependencies for tooling, peerDependencies must be supplied by the consumer.
Caret allows minor and patch updates, tilde only patch; the caret is stricter for 0.x versions.
Commit the lockfile; use npm ci in continuous integration for repeatable installs.
Audit dependencies; install scripts and packages are a supply chain risk.
Common mistakes
Putting build tools in dependencies, or runtime packages in devDependencies, so production installs break.
Using npm install in continuous integration and getting different versions from the lockfile.
Not committing the lockfile.
Using broad ranges such as star or latest for production dependencies.
Follow-ups
What is the difference between npm install and npm ci?
What is a peer dependency and why do plugins use it?
How would you protect a project from a malicious package?
Tips
Explain caret and tilde with one example each.
Say what the lockfile is for and when to use npm ci.
Separate runtime from development dependencies.
130.javascript-0130Easyfresher
What does TypeScript add to JavaScript, and what does it not do at runtime?
TypeScript is JavaScript plus a static type system. The compiler checks types before the code runs and then erases them, so the output is plain JavaScript with no runtime type checks. It catches mistakes such as wrong argument types, improves editor support, and documents code, but data from outside (JSON, user input, network) still needs runtime validation.
Full answer
TypeScript (TS) is a superset of JavaScript: valid JavaScript is valid TypeScript, with additional syntax for types. A compiler (tsc) or a tool such as esbuild, Babel, or SWC checks or removes the type syntax, and the result runs on any JavaScript engine. Recent Node.js versions can also run simple TypeScript files directly by removing the types, without checking them.
What it adds:
Static types: annotate variables, parameters, and return values. The compiler reports errors such as passing a string where a number is expected, reading a property that does not exist, or forgetting to handle undefined.
Inference: you often do not write types, because the compiler infers them from values.
Interfaces and type aliases, generics, unions (string | number), literal types, and narrowing: after if (typeof x === 'string'), the compiler knows the type inside the block.
Better editor tooling: autocomplete, safe renames, and go to definition.
A few runtime features, such as enum, which compile to real JavaScript. Many teams avoid enum and use unions of literals.
What it does not do: types are erased, so there is no runtime check. An as cast only tells the compiler to trust you. JSON.parse returns any, and a typed API response can still be wrong at runtime. Validate external data with a schema library or manual checks, and use the type system for the code you control.
Other points that interviewers ask about: any turns checking off for a value, and unknown forces you to check before use. A strict setting enables the most helpful checks and is the recommended starting point. TypeScript adds a build step and a learning cost, but it pays off in larger code bases and teams. JavaScript with JSDoc comments and checkJs can get part of the same checking without a build step.
Answer carefully when asked whether TypeScript is better: it helps with maintainability and refactoring, it does not remove the need for tests, and it does not make code faster.
javascript
const ts = require('typescript');
const source = `
interface User { name: string; age: number }
function greet(user: User, times: number): string {
return ('Hello ' + user.name + ' ').repeat(times).trim();
}
enum Color { Red, Green }
const parsed = JSON.parse('{"name":"Asha","age":"31"}') as User;
`;
// 1. Types are erased: the output is plain JavaScript
const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
console.log(output.trim());
// 2. Type checking happens before running, with an in-memory file
function check(code) {
const options = { strict: true, noEmit: true, target: ts.ScriptTarget.ES2022, lib: ['lib.es2022.d.ts'], types: [] };
const host = ts.createCompilerHost(options);
const original = host.getSourceFile.bind(host);
host.getSourceFile = (file, languageVersion) =>
file === 'input.ts' ? ts.createSourceFile(file, code, languageVersion) : original(file, languageVersion);
host.fileExists = (file) => file === 'input.ts' || ts.sys.fileExists(file);
host.readFile = (file) => (file === 'input.ts' ? code : ts.sys.readFile(file));
const program = ts.createProgram(['input.ts'], options, host);
return ts.getPreEmitDiagnostics(program).map((d) => {
const { line } = d.file.getLineAndCharacterOfPosition(d.start);
return `line ${line + 1}: ${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`;
});
}
console.log('--- valid code');
console.log(check(source + 'greet({ name: "Ben", age: 2 }, 2);'));
console.log('--- type errors found before running');
console.log(check(source + 'greet({ name: "Ben" }, "2");'));
console.log(check('function first(items: string[]) { return items[0].toUpperCase(); }\nfirst(42);'));
// 3. The cast above compiled, but the data is wrong at runtime
const parsed = JSON.parse('{"name":"Asha","age":"31"}');
console.log('typeof age at runtime:', typeof parsed.age, '(declared as number in the TypeScript source)');
console.log('TypeScript version used:', ts.version);
Run with Node.js v24.22.1 as js-130.js; two runs gave identical output.
Output:
function greet(user, times) {
return ('Hello ' + user.name + ' ').repeat(times).trim();
}
var Color;
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
})(Color || (Color = {}));
const parsed = JSON.parse('{"name":"Asha","age":"31"}');
--- valid code
[]
--- type errors found before running
[
"line 8: Argument of type '{ name: string; }' is not assignable to parameter of type 'User'. Property 'age' is missing in type '{ name: string; }' but required in type 'User'."
]
[
"line 2: Argument of type 'number' is not assignable to parameter of type 'string[]'."
]
typeof age at runtime: string (declared as number in the TypeScript source)
TypeScript version used: 5.9.3
Key points
TypeScript is JavaScript plus static types; the compiler checks them and then erases them.
It catches wrong types, missing properties, and unhandled undefined, and improves editor support.
No runtime checks: casts are trust, and external data needs validation.
any disables checks, unknown forces narrowing; start with strict mode.
It adds a build step; it does not replace tests or improve speed.
Common mistakes
Believing that types are checked at runtime.
Using as casts or any to silence errors instead of fixing the type or validating data.
Trusting the type of JSON from an API without validation.
Expecting TypeScript to remove the need for tests.
Follow-ups
What is the difference between any and unknown?
How do you validate untrusted data and keep the types in sync with the validation?
What is type narrowing, and how does a discriminated union use it?
Tips
Lead with "types are erased" and explain the consequences.
Mention validation for external data and the strict setting.
Be balanced: TypeScript helps maintenance and tooling but is not a substitute for tests.
131.javascript-0131Easyfresher
Predict the output of these type coercion and operator puzzles, and name the rule behind each result.
The plus operator concatenates when either side is a string and otherwise adds, while minus, multiply, and divide always convert to numbers. Comparison of two strings is alphabetical, a mixed comparison converts to numbers, and objects convert through valueOf and toString. Most surprises follow from these three rules plus the conversion of empty arrays, null, and undefined.
Full answer
Work through each puzzle with the rule, not by memory.
Rule 1: + with a string on either side concatenates, after converting the other side to a string. Otherwise it adds numbers. Arrays and objects first become primitives: [] becomes '', and {} becomes '[object Object]'. So [] + [] is '', [] + {} is '[object Object]', and 1 + '2' is '12'. Evaluation is left to right, so 1 + 2 + '3' is '33', while '1' + 2 + 3 is '123'.
Rule 2: -, *, / and % always convert both sides to numbers. So '5' - 2 is 3, '5' * '2' is 10, and 'abc' - 1 is NaN. The unary plus converts to a number too: +'42' is 42, +'' is 0, +[] is 0, +{} is NaN, and +null is 0, but +undefined is NaN.
Rule 3: loose equality == and relational operators convert. If both sides are strings, they are compared as text, so '10' < '9' is true. If one side is a number, the other becomes a number, so '10' < 9 is false. null == undefined is true, but null == 0 is false, because == treats null and undefined specially. null >= 0 is true, because relational operators convert null to 0. NaN is not equal to anything.
More traps: [1, 2] + [3] is '1,23' because both arrays become strings. [] == ![] is true: ![] is false, then [] becomes '', and both sides become 0. typeof null is 'object', a historic bug. 0.1 + 0.2 === 0.3 is false because of floating point. 'b' + 'a' + +'a' + 'a' gives 'baNaNa' because +'a' is NaN.
Advice: in real code, use ===, convert explicitly with Number() and String(), and use template literals for text. Puzzles are useful for learning the rules, but they should not appear in production code.
Plus concatenates if either side is a string after primitive conversion; minus, multiply, and divide convert to numbers.
Evaluation is left to right, so the position of the first string matters.
Unary plus converts to a number: empty string, empty array, and null give 0.
Two strings compare as text; mixed comparisons convert to numbers; null and undefined are only loosely equal to each other.
Use strict equality and explicit conversion in real code.
Common mistakes
Using == and expecting type-safe results.
Adding user input from forms without converting it, which concatenates strings.
Sorting numbers with the default sort, which compares text.
Memorizing puzzle answers without the three conversion rules.
Follow-ups
What is the difference between valueOf and toString when an object is converted?
How does Symbol.toPrimitive change conversion?
Why does typeof null return object?
Tips
Explain each answer through a rule, and name the rule.
Remember left to right evaluation for chained plus operators.
Close by saying that you use === and explicit conversion in real code.
132.javascript-0132Easyfresher
Which newer array, object, and set methods should a JavaScript developer know, such as toSorted, with, findLast, Object.groupBy, and Set union?
Recent JavaScript versions added non-mutating array methods (toSorted, toReversed, toSpliced, with), search helpers (findLast, findLastIndex, at), grouping (Object.groupBy and Map.groupBy), Set operations (union, intersection, difference), and Promise.withResolvers. They reduce manual copying and loops. Check runtime support before using them, because older browsers and Node.js versions do not have them.
Full answer
Many everyday tasks now have built-in methods that older code did by hand.
Non-mutating array methods (ES2023): sort, reverse, and splice change the original array, which causes bugs in shared state. Their copying versions are toSorted(compare), toReversed(), and toSpliced(start, deleteCount, ...items), and with(index, value) returns a copy with one element replaced. The originals stay untouched. This fits React state and other immutable patterns.
Finding from the end (ES2023): findLast(predicate) and findLastIndex(predicate) search backwards. at(-1) (ES2022) reads from the end without length - 1.
Grouping (ES2024): Object.groupBy(items, callback) returns a plain object with null prototype, whose keys are the strings the callback returns and whose values are arrays. Map.groupBy does the same but allows any key type, including objects.
Set methods (ES2025): union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, and isDisjointFrom take another set (or a set-like object) and return a new Set or a boolean.
Other useful additions: Object.hasOwn(obj, key) replaces hasOwnProperty.call, Object.fromEntries is the reverse of Object.entries, Array.prototype.flat and flatMap, structuredClone, String.prototype.replaceAll, Promise.withResolvers() (which returns a promise with its resolve and reject functions), and Array.fromAsync.
Support: these features are in current versions of Node.js and the main browsers, but not in older ones. For a library or a site with old browser requirements, check a compatibility table, and use a polyfill or a build step if needed. Do not assume a feature exists because it exists on your machine.
In interviews, show that you reach for the non-mutating forms in state updates and the grouping helpers in place of manual reduce code.
toSorted, toReversed, toSpliced, and with return copies instead of changing the array.
findLast, findLastIndex, and at read from the end.
Object.groupBy and Map.groupBy group items by a key function.
Set union, intersection, difference and related methods are built in now.
Check runtime support; use polyfills or a build step for older targets.
Common mistakes
Using sort or reverse on an array that belongs to shared state.
Assuming a new method exists in every target environment.
Writing manual reduce code for grouping when groupBy exists.
Using with and expecting it to grow the array: an index out of range throws.
Follow-ups
How would you polyfill toSorted for an older environment?
Why does Object.groupBy return an object with no prototype?
What is the difference between Object.groupBy and Map.groupBy?
Tips
Group the methods by purpose, not as a long list.
Mention support and polyfills, not only the methods.
Tie the non-mutating methods to immutable state updates.
133.javascript-0133Easyfresher
What is the difference between a plain script tag, async, defer, and type="module", and when does DOMContentLoaded fire?
A plain script blocks HTML parsing while it downloads and runs. With defer, the script downloads in parallel and runs in order after parsing finishes, before DOMContentLoaded. With async, it runs as soon as it is ready, in any order, which can interrupt parsing, and a module script is deferred by default. DOMContentLoaded fires when the HTML is parsed and deferred scripts have run, without waiting for images.
Full answer
The browser parses HTML from top to bottom. A script tag changes how that goes.
Plain <script src="a.js">: parsing stops, the file downloads, runs, and then parsing continues. Scripts in the head delay the first render, and a script in the head cannot see elements that are below it. It runs in document order with other plain scripts.
<script defer src>: the file downloads while parsing continues, and it runs after the document has been parsed, in the order the tags appear, before the DOMContentLoaded event. It is the best default for scripts that need the DOM. Defer applies only to external scripts.
<script async src>: the file downloads in parallel and runs as soon as it is ready, which can be before or after parsing is done, and the order between async scripts is not guaranteed. Use it for independent scripts, such as analytics, that do not depend on other scripts or on the DOM being complete.
<script type="module">: it is deferred by default (inline module scripts too), runs in strict mode, has its own scope, supports import, runs only once even if included twice, and with async added it runs as soon as it and its dependencies are loaded. Use nomodule to provide a fallback for very old browsers.
Events: DOMContentLoaded fires on document when the HTML is fully parsed and deferred and module scripts have run. It does not wait for images, stylesheets in some cases (they can block scripts), or subframes. The load event on window fires later, when all resources, including images, have loaded. document.readyState goes from loading to interactive to complete.
Practical code: if your script may run before or after DOMContentLoaded (for example, loaded with async), check document.readyState and run immediately if it is not loading. Also place scripts at the end of the body only for old setups; defer in the head is better because the download starts early.
javascript
const events = [];
const record = (name) => events.push(`${name} (readyState: ${document.readyState})`);
record('script starts');
document.addEventListener('readystatechange', () => record('readystatechange'));
document.addEventListener('DOMContentLoaded', () => record('DOMContentLoaded'));
window.addEventListener('load', () => record('load'));
// a helper that works whether the script runs before or after the document is ready
function onReady(callback) {
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', callback, { once: true });
else callback();
}
onReady(() => record('onReady callback'));
// a late script: registered after the document is already complete, so it must run immediately
setTimeout(() => {
onReady(() => record('late onReady callback runs at once'));
console.log(events.join('\n'));
}, 50);
Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output.
Output:
script starts (readyState: interactive)
onReady callback (readyState: interactive)
DOMContentLoaded (readyState: interactive)
readystatechange (readyState: complete)
load (readyState: complete)
late onReady callback runs at once (readyState: complete)
Key points
Plain script blocks parsing; defer runs in order after parsing; async runs when ready in any order.
Module scripts are deferred by default and run once in strict mode.
DOMContentLoaded waits for parsing and deferred scripts, not images; load waits for everything.
readyState moves from loading to interactive to complete.
Check readyState in scripts that may run late, and prefer defer in the head.
Common mistakes
Putting a blocking script in the head without defer.
Using async for scripts that depend on each other or on the DOM.
Waiting for DOMContentLoaded in a script that may run after the event, so the callback never runs.
Assuming DOMContentLoaded waits for images.
Follow-ups
Why does a module script not need the defer attribute?
Which event would you use to wait for images, and why is it usually too late?
How do preload and modulepreload help loading performance?
Tips
Describe the three timelines in one sentence each.
Recommend defer for DOM-dependent scripts and async for independent ones.
Show the readyState check for late-running code.
134.javascript-0134Hardsenior
What are ArrayBuffer, typed arrays, and DataView, and how do you work with binary data in JavaScript?
An ArrayBuffer is a fixed block of raw bytes. Typed arrays (Uint8Array, Float32Array, and others) are views that interpret those bytes as numbers of one type, and several views can share one buffer. DataView reads and writes mixed types at byte offsets with explicit endianness. Typed arrays are faster and more compact than normal arrays for numeric and binary data, and are used by files, network protocols, canvas, and WebGL.
Full answer
Normal arrays hold any values and are flexible. For binary data and large numeric data, JavaScript has a separate family.
ArrayBuffer: a block of bytes with a fixed length (new ArrayBuffer(16)), initialized to zeros. You cannot read it directly. You create a view.
Typed arrays: Uint8Array, Int16Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, and others. Each interprets the buffer as a sequence of one element type. new Uint8Array(buffer) and new Uint32Array(buffer) can look at the same bytes in different ways, and a write through one is seen through the other. Values wrap on overflow: storing 256 in a Uint8Array gives 0. Uint8ClampedArray clamps to 0 to 255 instead, which suits canvas pixel data.
Offsets: a view can start at a byteOffset and cover a length. subarray(start, end) creates another view on the same memory, while slice(start, end) copies. This difference causes many bugs: changing a subarray changes the original.
DataView: reads and writes individual values at byte positions, with a choice of endianness: getUint16(offset, littleEndian). Typed arrays always use the platform byte order (little endian on almost all current devices), so use DataView for file formats and network protocols, which define their own byte order.
Other points: TextEncoder and TextDecoder convert between strings and Uint8Array as UTF-8. Buffers can be transferred between threads without copying (postMessage with a transfer list), and shared with SharedArrayBuffer. Resizable buffers (new ArrayBuffer(8, { maxByteLength: 64 }) and resize) exist in current engines. In Node.js, Buffer is a Uint8Array subclass with extra methods.
Why use them: less memory (a million numbers in a Float64Array use 8 MB, with no per element object overhead), predictable layout, fast access, and the ability to pass data to native and GPU APIs.
javascript
const buffer = new ArrayBuffer(8);
const bytes = new Uint8Array(buffer);
const words = new Uint16Array(buffer);
bytes[0] = 1;
bytes[1] = 2;
console.log('same memory, two views:', bytes.slice(0, 4), words[0], '(0x0201 on a little endian machine)');
const small = new Uint8Array([250, 255]);
small[0] += 10;
console.log('wraps on overflow:', small[0], new Uint8ClampedArray([300, -5, 1.5, 2.5]));
const original = new Uint8Array([1, 2, 3, 4]);
const view = original.subarray(1, 3);
const copy = original.slice(1, 3);
view[0] = 99;
console.log('subarray shares:', original, 'slice copies:', copy, 'view offset:', view.byteOffset);
const record = new DataView(new ArrayBuffer(8));
record.setUint16(0, 0x1234); // big endian by default
record.setUint16(2, 0x1234, true); // little endian
record.setFloat32(4, 1.5, true);
console.log('bytes:', [...new Uint8Array(record.buffer)].map((b) => b.toString(16).padStart(2, '0')).join(' '));
console.log('read back:', record.getUint16(0), record.getUint16(0, true), record.getFloat32(4, true));
const text = new TextEncoder().encode('h\u00e9llo');
console.log(text, new TextDecoder().decode(text), text.length, 'h\u00e9llo'.length);
const floats = new Float64Array(1000000);
console.log('Float64Array of a million numbers uses', floats.byteLength, 'bytes');
const resizable = new ArrayBuffer(4, { maxByteLength: 16 });
resizable.resize(12);
console.log('resizable:', resizable.byteLength, resizable.resizable, resizable.maxByteLength);
const transferred = buffer.transfer();
console.log('after transfer: old detached =', buffer.detached, 'old length', buffer.byteLength, 'new length', transferred.byteLength);
console.log(Buffer.from([1, 2, 3]) instanceof Uint8Array);
Run with Node.js v24.22.1 as js-134.js; two runs gave identical output.
Output:
same memory, two views: Uint8Array(4) [ 1, 2, 0, 0 ] 513 (0x0201 on a little endian machine)
wraps on overflow: 4 Uint8ClampedArray(4) [ 255, 0, 2, 2 ]
subarray shares: Uint8Array(4) [ 1, 99, 3, 4 ] slice copies: Uint8Array(2) [ 2, 3 ] view offset: 1
bytes: 12 34 34 12 00 00 c0 3f
read back: 4660 13330 1.5
Uint8Array(6) [ 104, 195, 169, 108, 108, 111 ] héllo 6 5
Float64Array of a million numbers uses 8000000 bytes
resizable: 12 true 16
after transfer: old detached = true old length 0 new length 8
true
Key points
ArrayBuffer is raw fixed-size memory; typed arrays are views that give it a numeric type.
Several views can share one buffer; integer values wrap on overflow, and Uint8ClampedArray clamps.
subarray shares memory; slice copies.
DataView handles mixed types and explicit endianness for file and network formats.
TextEncoder and TextDecoder convert strings; buffers can be transferred or shared between threads.
Common mistakes
Assuming subarray copies, then changing the original by accident.
Using typed arrays with the platform byte order for a file format that defines big endian.
Expecting values to throw on overflow instead of wrapping.
Using a normal array of numbers for very large numeric data.
Follow-ups
How does transferring an ArrayBuffer to a Worker differ from sharing a SharedArrayBuffer?
How would you parse a binary file header with DataView?
Why is Uint8ClampedArray used for canvas pixel data?
Tips
Separate the three ideas: buffer is memory, typed array is a typed view, DataView is a flexible reader.
Say clearly that subarray shares and slice copies.
Mention endianness for file and network formats.
135.javascript-0135Hardsenior
What are mixins in JavaScript, how do you implement them, and what are the risks?
A mixin adds reusable behavior to a class without a single inheritance chain, because JavaScript classes can only extend one parent. Two common forms are copying methods onto a prototype with Object.assign and class factories (a function that takes a base class and returns a subclass). Risks include name collisions, hidden dependencies between mixins, and harder debugging, so keep mixins small and prefer composition when behavior is not truly shared.
Full answer
A class can extend only one parent. A mixin is a way to share behavior across unrelated classes without a deep hierarchy, such as adding serialize() or event methods to several classes.
Form 1, copying onto the prototype: Object.assign(User.prototype, canSerialize, canEmit). It is simple and works with plain objects, but copied methods are not on the prototype chain as classes, super inside them does not work as expected, and later changes to the mixin object are shared across all classes that got the same function references. Getters are evaluated during the copy by Object.assign, so use Object.defineProperties with descriptors for accessors.
Form 2, class factory (subclass factory): a function that takes a base class and returns a class that extends it.
const Serializable = (Base) => class extends Base { serialize() {...} }
Apply it by wrapping: class User extends Serializable(Person) {}, and combine several with Emitter(Serializable(Person)). Each application creates a new class in the chain, so super.method() works and the order is visible. Method resolution follows the chain, and the last mixin applied is closest to the instance.
Checks: instanceof does not know about a copied mixin. For factory mixins, you can add a Symbol.hasInstance check or a marker symbol, so hasMixin(obj, Serializable) works.
Risks and rules:
Name collisions: two mixins with the same method name silently override each other. Use clear names or symbols as keys.
Hidden coupling: a mixin that relies on fields of the host class breaks when those change. Document and check the requirements.
State: avoid mutable shared state in the mixin object, and initialize per-instance state in the constructor.
Debugging: long chains of anonymous classes produce confusing stack traces, so name the returned class.
Prefer composition (holding a helper object and delegating to it) when the behavior has its own state or the relationship is "has a", not "is a". Mixins fit small, stateless capabilities such as Comparable, Serializable, and event emitting.
javascript
// Form 1: copy methods onto a prototype
const canGreet = {
greet() {
return `Hi, I am ${this.name}`;
},
};
class Person {
constructor(name) {
this.name = name;
}
}
Object.assign(Person.prototype, canGreet);
console.log(new Person('Asha').greet());
// Form 2: class factories (subclass factories)
const Serializable = (Base) =>
class Serializable extends Base {
serialize() {
return JSON.stringify(this);
}
};
const Timestamped = (Base) =>
class Timestamped extends Base {
createdAt = 'fixed-for-demo';
describe() {
return `${super.describe()} [created ${this.createdAt}]`;
}
};
class Entity {
constructor(id) {
this.id = id;
}
describe() {
return `entity ${this.id}`;
}
}
class Product extends Timestamped(Serializable(Entity)) {
constructor(id, title) {
super(id);
this.title = title;
}
}
const product = new Product(7, 'Notebook');
console.log(product.serialize());
console.log(product.describe());
let proto = Object.getPrototypeOf(product);
const chain = [];
while (proto && proto !== Object.prototype) {
chain.push(proto.constructor.name);
proto = Object.getPrototypeOf(proto);
}
console.log('chain:', chain.join(' -> '));
// collisions: the mixin applied last wins
const A = (Base) => class extends Base { who() { return 'A'; } };
const B = (Base) => class extends Base { who() { return 'B'; } };
console.log(new (B(A(Object)))().who(), new (A(B(Object)))().who());
// detecting a mixin with a marker symbol
const isSerializable = Symbol('Serializable');
const Marked = (Base) => class extends Base { get [isSerializable]() { return true; } };
const hasMixin = (object, marker) => Boolean(object && object[marker]);
console.log(hasMixin(new (Marked(Entity))(1), isSerializable), hasMixin(new Entity(1), isSerializable));
console.log(product instanceof Entity, product instanceof Person);
Run with Node.js v24.22.1 as js-135.js; two runs gave identical output.
Output:
Hi, I am Asha
{"id":7,"createdAt":"fixed-for-demo","title":"Notebook"}
entity 7 [created fixed-for-demo]
chain: Product -> Timestamped -> Serializable -> Entity
B A
true false
true false
Key points
Mixins share behavior across classes despite single inheritance.
Object.assign onto a prototype is simple but copies by reference and does not support super or accessors well.
A class factory returns a subclass of the given base; it works with super and keeps a visible chain.
Risks: name collisions, hidden coupling, shared state, anonymous classes in stack traces.
Prefer composition for stateful or has-a relationships.
Common mistakes
Letting two mixins define the same method name without noticing.
Depending on fields of the host class inside the mixin without documenting it.
Putting mutable state on a shared mixin object.
Using mixins for a has-a relationship that composition expresses better.
Follow-ups
How do mixins compare with composition and with inheritance?
How does super work inside a class factory mixin?
How would you make instanceof work for a mixin?
Tips
Name both forms and say which you prefer: the class factory.
Show the collision rule: the last mixin applied wins.
End with when you would choose composition instead.
136.javascript-0136Hardsenior
When should you choose composition over inheritance in JavaScript, and what problems does deep inheritance cause?
Inheritance models an "is a" relationship and shares behavior through a prototype chain, while composition builds objects from smaller parts that they own and delegate to ("has a"). Deep hierarchies are rigid, create tight coupling to the base class (the fragile base class problem), and fail when behaviors need to be mixed in different combinations. Prefer composition for flexibility, and keep inheritance for shallow, true subtype relationships.
Full answer
Inheritance: class Dog extends Animal gives Dog all behavior of Animal and lets it override parts. It works well when there is a stable, honest subtype relationship and the base class is designed to be extended. Its costs:
Tight coupling: a subclass depends on the internal details of the base class, so a change in the base can break subclasses (the fragile base class problem). A classic example is a subclass of a collection that overrides add and addAll, where addAll in the base calls add, so items get counted twice.
Rigidity: the hierarchy is fixed at design time. If a Robot and a Duck both need fly, but only some robots swim and some ducks do not, a tree of classes cannot express every combination. You end up with duplicated code or a big base class.
The gorilla and banana problem: you wanted a banana, but you got a gorilla holding the banana and the whole jungle, meaning inherited methods and state you do not want.
Hard testing: a subclass cannot be tested without its ancestors.
Composition: build an object from small, focused parts and delegate to them. A Robot has a mover, a speaker, and a battery. Behaviors are plain functions or small objects that can be swapped, tested alone, and combined freely. In JavaScript this is natural: factory functions that return objects, object spread to combine capabilities, dependency injection through constructor arguments, and functions as strategy values.
Rules of thumb:
Ask "is X a kind of Y in all cases?" If not, do not inherit.
Prefer a shallow hierarchy, ideally one or two levels.
Inherit from abstractions designed for it (such as Error, EventTarget, and framework base classes), and compose everything else.
Share small pieces of behavior with functions, mixins, or helper objects.
Inheritance is not wrong. The point is to choose it for subtype relationships, and use composition for sharing behavior. Frameworks have moved in this direction: React uses composition of components and hooks instead of class inheritance for sharing logic.
javascript
// 1. The fragile base class problem
class CountingList {
items = [];
add(item) {
this.items.push(item);
}
addAll(list) {
for (const item of list) this.add(item);
}
}
class CountingListWithTotal extends CountingList {
total = 0;
add(item) {
this.total++;
super.add(item);
}
addAll(list) {
this.total += list.length;
super.addAll(list); // the base class calls this.add for each item, so every item is counted twice
}
}
const inherited = new CountingListWithTotal();
inherited.addAll(['a', 'b', 'c']);
console.log('inheritance: items', inherited.items.length, 'total', inherited.total);
// 2. The same feature with composition: wrap a list and delegate to it
class CountedList {
#list = new CountingList();
total = 0;
add(item) {
this.total++;
this.#list.add(item);
}
addAll(list) {
for (const item of list) this.add(item);
}
get items() {
return [...this.#list.items];
}
}
const composed = new CountedList();
composed.addAll(['a', 'b', 'c']);
console.log('composition: items', composed.items.length, 'total', composed.total);
// 3. Combining capabilities freely with factory functions
const canWalk = (state) => ({ walk: () => `${state.name} walks` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });
const canFly = (state) => ({ fly: () => `${state.name} flies` });
const canSpeak = (state, sound) => ({ speak: () => `${state.name} says ${sound}` });
function createDuck(name) {
const state = { name };
return { ...canWalk(state), ...canSwim(state), ...canFly(state), ...canSpeak(state, 'quack') };
}
function createRobot(name) {
const state = { name };
return { ...canWalk(state), ...canFly(state), ...canSpeak(state, 'beep') };
}
function createPenguin(name) {
const state = { name };
return { ...canWalk(state), ...canSwim(state), ...canSpeak(state, 'honk') };
}
const all = [createDuck('Duck'), createRobot('Robot'), createPenguin('Penguin')];
console.log(all.map((x) => Object.keys(x).join('/')));
console.log(all.map((x) => x.speak()), all[2].fly === undefined);
// 4. Dependency injection: behavior supplied from outside, easy to replace in tests
class Notifier {
constructor(send) {
this.send = send;
}
notify(user) {
return this.send(`Hello ${user}`);
}
}
const sent = [];
console.log(new Notifier((message) => sent.push(message)).notify('Asha'), sent);
Run with Node.js v24.22.1 as js-136.js; two runs gave identical output.
Output:
inheritance: items 3 total 6
composition: items 3 total 3
[ 'walk/swim/fly/speak', 'walk/fly/speak', 'walk/swim/speak' ]
[ 'Duck says quack', 'Robot says beep', 'Penguin says honk' ] true
1 [ 'Hello Asha' ]
Key points
Inheritance is "is a"; composition is "has a" with delegation.
Deep inheritance causes tight coupling, fragile base classes, and rigid combinations.
Composition lets you swap, test, and combine small parts, using factories, spread, and injection.
Use inheritance for true subtypes and for classes designed to be extended, such as Error.
Keep hierarchies shallow and share behavior with functions or helper objects.
Common mistakes
Inheriting just to reuse a few methods when the relationship is not "is a".
Overriding a method that the base class calls internally.
Building hierarchies three or more levels deep.
Treating composition as a rule that bans inheritance.
Follow-ups
How do mixins relate to composition and inheritance?
Why do frameworks such as React prefer composition?
How would you decide whether Error subclasses are a good use of inheritance?
Tips
Give the double counting example; it is memorable and concrete.
Say when inheritance is still right.
Mention factory functions and dependency injection as the JavaScript tools for composition.
137.javascript-0137Hardsenior
What does a JavaScript bundler do, and how does tree shaking remove unused code?
A bundler follows import statements from an entry file, combines the modules into a few files, and can transform, minify, and split them for fast loading. Tree shaking removes exports that are never used, relying on the static structure of ES modules. It works poorly with CommonJS and with code that has side effects, so use ESM, avoid side effects at module level, and mark packages with the sideEffects field.
Full answer
Browsers can load ES modules, but a real application can have hundreds of modules and dependencies. A bundler (webpack, Rollup, esbuild, Vite and Parcel use these or similar tools) builds the dependency graph starting from entry files, then outputs optimized bundles. It also handles other things: transforming TypeScript and JSX, minifying, processing CSS and assets, code splitting (separate files loaded on demand through import()), content hashes for caching, and development servers with hot reload.
Tree shaking is dead code elimination across modules: the bundler marks which exports are used and drops the rest. It works because ES module import and export are static. They cannot be conditional and their names are known at build time, so the tool can analyze them without running code. CommonJS require is dynamic (it can be called in an if with a computed path), so tools usually have to keep the whole module.
What blocks tree shaking:
CommonJS modules, or a library that publishes only CommonJS.
Side effects at module level. A top-level call like registerPlugin() or a patch of a global must run when the module loads, so the bundler cannot remove the module without changing behavior. Pure marked calls (/* @__PURE__ */) tell the tool that a call can be removed if its result is unused.
Barrel files (index.js that re-exports everything) combined with a package that is not marked side-effect free.
Classes with static properties and other constructs that the tool cannot prove are pure.
Controls: the sideEffects field in package.json can be false (no module in the package has side effects, so unused modules can be dropped) or a list of files that do have them (such as CSS files). Write libraries as ES modules, export many small functions instead of one big object, and import only what you need (import { debounce } from 'lib').
Measure rather than guess: check the output size, use a bundle analyzer, and compare the result of production mode builds, because tree shaking and minification often only run there. The snippet bundles virtual modules with esbuild, in memory, to show the effect.
javascript
const esbuild = require('esbuild');
const files = {
'entry-esm.js': `import { used } from './lib-esm.js'; console.log(used());`,
'lib-esm.js': `
export function used() { return 'used function'; }
export function unusedOne() { return 'UNUSED_MARKER_ONE'; }
export const unusedTwo = ['CALL_MARKER'].map((text) => text + '!');
export const unusedThree = /* @__PURE__ */ ['PURE_MARKER'].map((text) => text + '!');
`,
'entry-cjs.js': `const lib = require('./lib-cjs.js'); console.log(lib.used());`,
'lib-cjs.js': `
exports.used = function () { return 'used function'; };
exports.unusedOne = function () { return 'UNUSED_MARKER_ONE'; };
`,
'entry-effect.js': `import { used } from './lib-effect.js'; console.log(used());`,
'lib-effect.js': `
globalThis.registered = 'SIDE_EFFECT_MARKER';
export function used() { return 'used function'; }
export function unusedOne() { return 'UNUSED_MARKER_ONE'; }
`,
};
const virtual = {
name: 'virtual-files',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => ({ path: args.path.replace('./', ''), namespace: 'virtual' }));
build.onLoad({ filter: /.*/, namespace: 'virtual' }, (args) => ({ contents: files[args.path], loader: 'js' }));
},
};
async function bundle(entry) {
const result = await esbuild.build({
entryPoints: [entry],
bundle: true,
write: false,
format: 'esm',
plugins: [virtual],
logLevel: 'silent',
});
return result.outputFiles[0].text;
}
async function main() {
const esm = await bundle('entry-esm.js');
console.log('ESM bundle keeps the used function:', esm.includes('used function'));
console.log('ESM bundle drops unusedOne:', !esm.includes('UNUSED_MARKER_ONE'));
console.log('unused export with a plain call is kept:', esm.includes('CALL_MARKER'));
console.log('unused export marked as pure is dropped:', !esm.includes('PURE_MARKER'));
const cjs = await bundle('entry-cjs.js');
console.log('CommonJS bundle still contains unusedOne:', cjs.includes('UNUSED_MARKER_ONE'));
const effect = await bundle('entry-effect.js');
console.log('module with a side effect keeps the global assignment:', effect.includes('SIDE_EFFECT_MARKER'));
console.log('and still drops unusedOne:', !effect.includes('UNUSED_MARKER_ONE'));
console.log('esbuild version:', esbuild.version);
}
main();
Run with Node.js v24.22.1 as js-137.js; two runs gave identical output.
Output:
ESM bundle keeps the used function: true
ESM bundle drops unusedOne: true
unused export with a plain call is kept: true
unused export marked as pure is dropped: true
CommonJS bundle still contains unusedOne: true
module with a side effect keeps the global assignment: true
and still drops unusedOne: true
esbuild version: 0.28.2
Key points
A bundler builds a module graph, combines, transforms, minifies, and splits code.
Tree shaking removes unused exports using the static structure of ES modules.
CommonJS, top-level side effects, and impure initialization block it.
Use the sideEffects field, pure annotations, ES module output, and small exports.
Measure with the production build and a bundle analyzer.
Common mistakes
Publishing a library only as CommonJS and then expecting tree shaking.
Putting side effects at the top level of modules in a library.
Importing a whole library when only one function is needed.
Judging bundle size from a development build.
Follow-ups
What is the difference between tree shaking and code splitting?
What does the sideEffects field in package.json mean?
Why are barrel files sometimes a problem for bundle size?
Tips
Explain that ES module imports are static, and so analyzable.
Name what blocks tree shaking: CommonJS and side effects.
Mention measuring with the production build and an analyzer.
138.javascript-0138Hardsenior
How does client-side routing work with the History API, and how would you build a minimal router?
A single-page app changes the visible URL without a page load using history.pushState or replaceState, renders the matching view itself, and listens for the popstate event to handle the back and forward buttons. A router matches the path against route patterns, extracts parameters, intercepts clicks on same-origin links, and needs a server fallback to the app shell so direct visits to deep URLs work.
Full answer
In a normal site, each link triggers a request for a new HTML page. In a single-page application (SPA), JavaScript handles navigation. The History API makes that possible:
history.pushState(state, '', url) adds an entry and changes the URL without loading anything.
history.replaceState(state, '', url) changes the current entry (for redirects and cleaning query strings).
The popstate event fires on window when the user moves through history with back or forward. It does not fire for pushState calls, so the router renders after its own calls.
history.back(), forward(), and go(n) move through the entries. history.state holds the state object of the current entry.
A minimal router does four things:
Route table: patterns such as /users/:id converted to regular expressions, with named parameters.
Navigation: navigate(path) calls pushState and then renders. A render() function reads location.pathname, finds the match, and calls its handler with the parameters.
Link interception: listen for clicks on the document. For an a element on the same origin, with no modifier keys, no target, and a left click, call preventDefault and navigate. Let the browser handle everything else, such as ctrl-click to open a new tab.
Back and forward: on popstate, call render() again.
Server side: a visit to /users/7 sends a request to the server, which must return the app shell (the same HTML file) for unknown paths, or the page shows a 404. Also handle scroll restoration, focus management and the page title for accessibility, a not found route, and the base path if the app is not served from the root.
The older alternative is hash routing (#/users/7), which needs no server configuration. The newer Navigation API (navigation.navigate, navigate event) is a more complete replacement for the History API in current browsers, and the View Transitions API can animate page changes.
Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output.
Output:
first render / | Home page | entries: 1
click user link /users/7?tab=posts | User 7, tab posts | entries: 2
navigate in code /users/42 | User 42, tab none | entries: 3
unknown route /missing | Not found: /missing | entries: 4
replace with home / | Home page | entries: 4
after back /users/42 | User 42, tab none | entries: 4
after forward / | Home page | entries: 4
same origin as the page (router would intercept): true false
Key points
pushState and replaceState change the URL without loading; popstate fires on back and forward only.
A router has a route table with params, a render function, link interception, and popstate handling.
Intercept only plain same-origin left clicks; let other clicks use the browser default.
The server must return the app shell for deep URLs.
Handle scroll, focus, title, and not found; hash routing and the Navigation API are alternatives.
Common mistakes
Expecting popstate to fire after pushState.
Intercepting every click, including ctrl-click, external links, and downloads.
Forgetting the server fallback, so refreshing a deep URL gives a 404.
Not updating the page title and focus after a route change, which hurts accessibility.
Follow-ups
What are the trade-offs between hash routing and History API routing?
How would you restore scroll position on back navigation?
What does the Navigation API improve over the History API?
Tips
Say that pushState does not fire events, so the router must render itself.
List which clicks to intercept and which to leave alone.
Mention the server fallback and accessibility.
139.javascript-0139Hardsenior
What is an unhandled promise rejection, what happens when one occurs in Node.js and in the browser, and how do you prevent them?
A promise that rejects with no handler attached by the end of the current microtask processing is an unhandled rejection. Node.js emits unhandledRejection and, by default since version 15, treats it as an uncaught exception and exits with an error. Browsers fire an unhandledrejection event and log a console error. Prevent it by always awaiting or catching promises, never leaving floating promises, and adding a global handler for logging.
Full answer
A rejected promise is a failure that must be handled with catch, then(_, onRejected), or try and catch around await. If no handler is attached when the engine checks, the rejection is unhandled, which usually means a bug: an error that nobody sees.
Node.js: the process emits unhandledRejection (with the reason and the promise). Since Node.js 15, the default mode is throw: if there is no unhandledRejection listener, the rejection becomes an uncaught exception, which prints the error and exits with code 1. If a handler exists, Node.js calls it and continues. If a handler is attached later, rejectionHandled is emitted. Production code should log the error in the global handler and then treat it as fatal when the process state is uncertain (shut down gracefully and let the process manager restart it).
Browser: the window fires an unhandledrejection event (with event.reason and event.promise) and the console shows an error. event.preventDefault() suppresses the console message. Use it for error reporting.
Common causes of unhandled rejections:
A floating promise: calling an async function without await or catch.
array.forEach(async (x) => {...}): forEach ignores the returned promises, so errors escape the surrounding try. Use for...of with await, or Promise.all(array.map(...)).
new Promise(async (resolve) => ...): an error thrown inside an async executor becomes a rejection of a different promise that nobody has.
Event handlers and timers with async functions: errors are not caught by the code that registered them.
Promise.all with several rejections: after the first rejection, the others are handled internally by Promise.all, so they do not cause extra reports, but their errors are lost. Use allSettled when you need all outcomes.
Prevention: await everything or return it, add a final .catch to top-level promises (main().catch(handle)), enable a lint rule such as no-floating-promises (typescript-eslint) and no-misused-promises, and register global handlers to log what slips through. Do not use a global handler to hide errors.
javascript
const { spawnSync } = require('node:child_process');
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const events = [];
process.on('unhandledRejection', (reason) => events.push('unhandledRejection: ' + reason.message));
process.on('rejectionHandled', () => events.push('rejectionHandled (a handler was attached late)'));
async function main() {
// 1. A rejection nobody handles
Promise.reject(new Error('floating promise'));
await wait(20);
// 2. A handler attached too late: first reported, then marked as handled
const late = Promise.reject(new Error('handled late'));
await wait(20);
late.catch(() => events.push('late catch ran'));
await wait(20);
// 3. forEach with an async callback: the try/catch does not see the error
try {
[1].forEach(async () => {
throw new Error('inside forEach callback');
});
events.push('try block finished without catching the forEach error');
} catch (error) {
events.push('caught: ' + error.message);
}
await wait(20);
// 4. The correct form: for...of with await
try {
for (const item of [1]) {
await (async () => {
throw new Error('inside for-of loop');
})();
}
} catch (error) {
events.push('caught: ' + error.message);
}
// 5. Promise.all rejects once; the other rejection is handled internally and lost
try {
await Promise.all([Promise.reject(new Error('first')), Promise.reject(new Error('second'))]);
} catch (error) {
events.push('Promise.all rejected with: ' + error.message);
}
await wait(20);
console.log(events.join('\n'));
// 6. Default behavior without a handler: a separate process exits with code 1
const child = spawnSync(process.execPath, ['-e', "Promise.reject(new Error('no handler'))"]);
console.log('exit code without a handler:', child.status);
const withHandler = spawnSync(process.execPath, ['-e', "process.on('unhandledRejection', () => {}); Promise.reject(new Error('x'))"]);
console.log('exit code with a handler:', withHandler.status);
}
main();
Run with Node.js v24.22.1 as js-139.js; two runs gave identical output.
Output:
unhandledRejection: floating promise
unhandledRejection: handled late
late catch ran
rejectionHandled (a handler was attached late)
try block finished without catching the forEach error
unhandledRejection: inside forEach callback
caught: inside for-of loop
Promise.all rejected with: first
exit code without a handler: 1
exit code with a handler: 0
Key points
A rejection with no handler when microtasks settle is unhandled; it usually hides a bug.
Node.js default since version 15: it becomes an uncaught exception and the process exits with code 1.
Browsers fire unhandledrejection and log an error; Node.js also has rejectionHandled for late handlers.
Prevent with await or catch everywhere, lint rules, and global handlers used for logging.
Common mistakes
Calling async functions without await or catch.
Using forEach with an async callback and expecting try and catch around it to work.
Writing new Promise(async (resolve, reject) => ...).
Using a global handler to silence errors instead of logging and fixing the cause.
Follow-ups
What is the difference between unhandledRejection and uncaughtException in Node.js?
Why does array.map with async callbacks plus Promise.all work where forEach does not?
How would you configure a lint rule to find floating promises?
Tips
Describe the Node.js default behavior and the browser event.
List the three usual causes: floating, forEach, async executor.
Say that global handlers are for logging, not for hiding problems.
140.javascript-0140Hardsenior
What are async generators and for await...of, and when would you use them, for example for pagination or streaming data?
An async generator (async function*) produces a sequence of values over time, awaiting between them, and for await...of consumes it one value at a time. It suits paginated APIs, streams, and event sources because values are produced lazily, backpressure is natural (the next item is requested only after the loop body finishes), and breaking out of the loop runs the generator's cleanup code in finally blocks.
Full answer
A normal generator yields values synchronously. An async generator is declared with async function*, can use await inside, and its yield produces a promise-wrapped value. It returns an object with Symbol.asyncIterator, and each next() call returns a promise of { value, done }. You consume it with for await (const item of source), which also accepts sync iterables of promises, and works in an async function or at module top level.
Why use it:
Pagination: write the loop that fetches page after page inside the generator and yield each item. The caller sees a flat sequence and does not know about pages. The next page is fetched only when the consumer asks for more.
Backpressure: the generator pauses at yield until the consumer calls next() again. A slow consumer slows the producer, so there is no unbounded buffer, unlike an event emitter.
Streams: Node.js readable streams, the readline interface, and the fetch response body (for await (const chunk of response.body) works in Node.js and in some browsers) are async iterable.
Cleanup: if the consumer leaves the loop early with break, return, or by throwing, the engine calls the generator's return() method, which runs its finally blocks. Close connections or file handles in finally.
Composition: write small async generator functions, such as map, filter, and take, and chain them, like lazy pipelines.
Details: the generator runs one next() at a time (requests are queued), errors thrown in the generator reject the pending next() promise and end the loop, and an await inside for await loops is sequential. For parallel work use Promise.all with batches instead.
To make your own class async iterable, define [Symbol.asyncIterator]() { return { next() {...} } }, or simply write async *[Symbol.asyncIterator]().
An async generator that never finishes, such as one that polls a feed, needs an exit condition or an AbortSignal, otherwise the loop runs forever.
javascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];
// a fake paginated API
const database = Array.from({ length: 7 }, (_, i) => `item-${i + 1}`);
async function fetchPage(page, size) {
await sleep(1);
log.push(`fetching page ${page}`);
const items = database.slice((page - 1) * size, page * size);
return { items, hasMore: page * size < database.length };
}
async function* paginate(size) {
let page = 1;
try {
while (true) {
const { items, hasMore } = await fetchPage(page++, size);
yield* items;
if (!hasMore) return;
}
} finally {
log.push('paginate cleanup ran');
}
}
async function* take(source, count) {
if (count <= 0) return;
let taken = 0;
for await (const item of source) {
yield item;
if (++taken >= count) return;
}
}
async function* map(source, fn) {
for await (const item of source) yield fn(item);
}
class Countdown {
constructor(from) {
this.from = from;
}
async *[Symbol.asyncIterator]() {
for (let n = this.from; n > 0; n--) {
await sleep(1);
yield n;
}
}
}
async function main() {
const all = [];
for await (const item of paginate(3)) all.push(item);
console.log(all.length, 'items,', log.filter((line) => line.startsWith('fetching')).length, 'pages fetched');
log.length = 0;
for await (const item of paginate(3)) {
if (item === 'item-2') break; // leaving early runs the finally block
}
console.log(log);
log.length = 0;
const firstFour = [];
for await (const item of map(take(paginate(2), 4), (text) => text.toUpperCase())) firstFour.push(item);
console.log(firstFour, log);
const countdown = [];
for await (const n of new Countdown(3)) countdown.push(n);
console.log(countdown);
for await (const value of [Promise.resolve('a'), 'b', sleep(1).then(() => 'c')]) process.stdout.write(value + ' ');
console.log('(for await over an array of promises)');
async function* failing() {
yield 1;
throw new Error('source failed');
}
try {
for await (const value of failing()) console.log('got', value);
} catch (error) {
console.log('caught:', error.message);
}
}
main();
Run with Node.js v24.22.1 as js-140.js; two runs gave identical output.
Output:
7 items, 3 pages fetched
[ 'fetching page 1', 'paginate cleanup ran' ]
[ 'ITEM-1', 'ITEM-2', 'ITEM-3', 'ITEM-4' ] [ 'fetching page 1', 'fetching page 2', 'paginate cleanup ran' ]
[ 3, 2, 1 ]
a b c (for await over an array of promises)
got 1
caught: source failed
Key points
async function* yields values over time; for await consumes them one at a time.
Great for pagination, streams, and event sources, hiding the pages from the caller.
Natural backpressure: the producer waits until the consumer asks for the next value.
Leaving the loop early calls return(), so finally blocks clean up resources.
Own classes can define Symbol.asyncIterator; add an abort signal for endless sources.
Common mistakes
Using forEach or map with await and expecting sequential asynchronous iteration.
Forgetting cleanup in finally, so connections stay open when the consumer stops early.
Writing an endless polling generator with no way to stop it.
Awaiting independent items one by one when parallel work would be faster.
Follow-ups
What happens to queued next() calls on an async generator?
How do Node.js readable streams use async iteration, and what are the backpressure implications?
How would you add cancellation with AbortSignal to an async generator?
Tips
Explain pagination as the motivating example.
Mention backpressure and finally-based cleanup.
Show that for await also accepts async iterables you build with Symbol.asyncIterator.