JavaScript Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How many data types does JavaScript have according to the specification?
Correct answer: 8: seven primitives and
objectPrimitives:
number,bigint,string,boolean,null,undefined,symbol. Everything else isobject, including arrays, functions and dates. Functions are objects, even thoughtypeofreturns'function'for them.2. What does
typeof nullreturn?Correct answer:
'object'It's a historical bug from the language's first implementation, kept for compatibility.
nullis a separate primitive. Check for it with strict equality:value === null.3. What does
typeof NaNreturn?Correct answer:
'number'NaN(Not-a-Number) is a special value of the number type, the result of an invalid math operation such as0 / 0orNumber('abc'). Check for it withNumber.isNaN(x).4. How does
letdiffer fromvar?Correct answer:
letis scoped to a{}block,varto a functionA
vardeclared inside aniforforis visible throughout the function. Also,varis hoisted with the valueundefinedand becomes awindowproperty at the top level, whileletandconstare in the "temporal dead zone" until declared.5. What happens?
const user = { name: "Ann" }; user.name = "Bob";Correct answer: It works:
constforbids reassignment, not mutation of the objectconstfixes the reference:user = {}throws, but the object's contents can change. To prevent property changes, useObject.freeze(shallowly).6. What does this code print?
console.log(x); var x = 5;Correct answer:
undefinedThe
vardeclaration is hoisted to the top of the function and initialized withundefined, while the assignment stays in place. Withletorconstthis would be aReferenceError.7. What does this code print?
console.log(y); let y = 5;Correct answer:
ReferenceErrorletandconstare hoisted too, but until the declaration line they're in the temporal dead zone (TDZ): any access throws aReferenceError. This helps catch variables used before initialization.8. How does
==differ from===?Correct answer:
==coerces types before comparing,===compares without coercion0 == ''and'1' == 1aretruebecause of coercion, butfalsewith===. Loose equality rules are confusing, so===is almost always used. A handy exception:x == nullchecks for bothnullandundefinedat once.9. How does
nulldiffer fromundefined?Correct answer:
undefinedmeans no value was assigned,nullis an explicit "empty" set by the programmerundefinedis what uninitialized variables, missing properties and parameters, and functions withoutreturnproduce.nullis assigned on purpose.null == undefinedistrue, butnull === undefinedisfalse.10. What does
NaN === NaNreturn?Correct answer:
falseNaNis not equal to anything, not even itself. UseNumber.isNaN(x)orObject.is(x, NaN)to check. The globalisNaN('abc')coerces its argument to a number first and returnstruefor strings.11. What does
0.1 + 0.2 === 0.3evaluate to?Correct answer:
falseNumbers are stored in binary IEEE-754 format, and 0.1 and 0.2 can't be represented exactly - the sum is
0.30000000000000004. Compare numbers with a tolerance (Math.abs(a - b) < Number.EPSILON), and handle money as integer cents.12. What are
'5' + 3and'5' - 3?Correct answer:
'53'and2If one operand of
+is a string, concatenation happens. Other arithmetic operators convert operands to numbers. That's why values frominput.valueare converted withNumber()before adding.13. Which of these values is falsy?
Correct answer:
0Falsy values:
false,0,-0,0n,'',null,undefined,NaN. Everything else is truthy, including the string'0', an empty array[]and an empty object{}.14. How does
count || 10differ fromcount ?? 10whencount = 0?Correct answer:
||returns10, while??returns0||substitutes the fallback for any falsy value, while??only does so fornullandundefined. For numbers and strings where0and''are valid values,??is the right choice.15. What does
user?.address?.cityreturn ifuser = {}?Correct answer:
undefinedOptional chaining short-circuits and returns
undefinedif the value on the left isnullorundefined. Without?.,user.address.citywould throw aTypeError. There are also forms for callsfn?.()and indexesarr?.[0].16. How does an arrow function differ from a regular one?
Correct answer: It has no own
thisorargumentsand can't be called withnewAn arrow takes
thisfrom the scope where it was created, which makes it handy for callbacks inside methods. But it doesn't work as an object method:thiswon't point to the object. Only function declarations are fully hoisted.17. Can you call a function before its declaration?
greet(); function greet() { console.log("hi"); }Correct answer: Yes: a function declaration is fully hoisted
Function declarations are created before code in their scope runs. With a function expression (
const greet = function () {}), calling before the declaration fails: the variable is in the TDZ (orundefinedwithvar).18. What does this code print?
function makeCounter() { let count = 0; return () => ++count; } const c = makeCounter(); c(); c(); console.log(c());Correct answer:
3This is a closure: the returned function remembers the
countvariable from the scope where it was created, and each call increments it. CallingmakeCounter()again would create an independent counter.19. What is a closure?
Correct answer: A function together with access to variables of the outer scope where it was created
Every JS function remembers the lexical environment where it was created and can read and change its variables even after the outer function finishes. Private data, function factories, memoization and event handlers are built on this.
20. What does this code print?
const a = { n: 1 }; const b = a; b.n = 2; console.log(a.n);Correct answer:
2Objects are passed by reference:
bpoints to the same object asa. To get a copy, use spread{ ...a }(shallow) orstructuredClone(a)(deep).21. What does
const copy = { ...original }do?Correct answer: A shallow copy: nested objects remain shared
Spread copies only own first-level properties. If
original.addressis an object, it's shared by both copies.structuredClonegives a deep copy, but it doesn't copy functions or DOM nodes.22. What does
[1, 2, 3].map(x => x * 2)return?Correct answer:
[2, 4, 6]mapcreates a new array from the callback's results without changing the original. Similar non-mutating methods:filter(selection),reduce(folding into one value),find,some,every.23. What does
[1, 2, 3].forEach(x => x * 2)return?Correct answer:
undefinedforEachis for side effects and always returnsundefined. Usemapto get a new array. Another difference: you can'tbreakout offorEach- usefor...of,someorfindfor that.24. What does
[1, 2, 3, 4].reduce((sum, x) => sum + x, 0)return?Correct answer:
10reducewalks the array, passing the accumulator from step to step; the second argument is the initial value. Without it, the first element becomes the initial accumulator, and an empty array throws aTypeError.25. How does
for...indiffer fromfor...of?Correct answer:
for...initerates over object keys,for...ofover values of an iterablefor (const key in obj)goes over enumerable string keys, including inherited ones.for (const item of arr)works with iterables: arrays, strings,Map,Set.for...inisn't suitable for arrays - it yields indexes as strings.26. How does
slicediffer fromsplice?Correct answer:
slicereturns part of the array without changes,splicemutates the originalarr.slice(1, 3)creates a new array.arr.splice(1, 2, 'x')removes and inserts elements inarritself. The non-mutating alternative istoSpliced(). Other mutating methods:push,pop,shift,sort,reverse.27. What do
[NaN].includes(NaN)and[NaN].indexOf(NaN)return?Correct answer:
trueand-1indexOfuses strict equality===, andNaN !== NaN.includesuses the SameValueZero algorithm, which treatsNaNas equal to itself. Soincludesis more reliable for checking presence.28. What does this code print?
const { name = "Guest", age } = { age: 30 }; console.log(name, age);Correct answer:
Guest 30Destructuring extracts properties into variables, and the default value is used when the property is
undefined. You can rename ({ name: userName }) and destructure nested objects and arrays.29. What does
sum(1, 2, 3)return?function sum(...nums) { return nums.length; }Correct answer:
3A rest parameter collects the remaining arguments into a real array. Unlike the legacy
arguments, it's an array withmapandreduce, and it works in arrow functions.30. What does
Math.max(...[3, 7, 2])return?Correct answer:
7Spread "expands" the array into separate arguments:
Math.max(3, 7, 2). Without spread,Math.max([3, 7, 2])returnsNaN. Spread is also used to copy and merge arrays and objects.31. What does
JSON.stringify({ a: 1, b: undefined, c: () => 1 })return?Correct answer:
'{"a":1}'Properties whose values are
undefined, functions or symbols are skipped (in arrays they becomenull).Datebecomes a string,MapandSetbecome{}. Circular references throw an error.32. In what order are the numbers printed?
console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4);Correct answer:
1 4 3 2Synchronous code runs first (1, 4). Then the event loop runs all microtasks - promise callbacks (3) - and only then the next macrotask - the timer (2).
setTimeout(fn, 0)doesn't mean "immediately".33. Which states can a promise be in?
Correct answer:
pending, thenfulfilledorrejected- and it never changes againA promise starts pending and settles exactly once into fulfilled or rejected. Further
resolve/rejectcalls are ignored. A promise can't be cancelled - useAbortControllerto cancel operations.34. What does an
asyncfunction return?Correct answer: Always a promise, even with
return 42insideasync function f() { return 42 }returnsPromise<42>. An exception inside becomes a rejected promise. That's why the result is obtained withawaitor.then().35. Why won't
catchcatch the error?try { fetch("/api").then(r => { throw new Error("fail"); }); } catch (e) { console.log("caught"); }Correct answer: The error happens later, after
tryhas already finishedThe
tryblock ran synchronously and finished before the server responded. Errors in the chain are caught with.catch(), or by writingawait fetch(...)insidetryin an async function - thencatchworks.36. What does
const arr = ['a', 'b']; console.log(arr[20]);print?Correct answer:
undefinedAccessing a nonexistent index, like a missing object property, returns
undefinedwithout an error. For the last element,arr.at(-1)is handy.37. What does this code print?
const s = "hello"; s[0] = "H"; console.log(s);Correct answer:
helloStrings are immutable: you can't change a character; the assignment is silently ignored (a
TypeErrorin strict mode). You need to create a new string:s[0].toUpperCase() + s.slice(1).38. How do you reliably check that a value is an array?
Correct answer:
Array.isArray(value)typeof []returns'object', and strings and array-like objects also havelength.Array.isArrayworks even for arrays from other iframes, whereinstanceof Arrayfails.39. Why is
textContentsafer thaninnerHTMLfor displaying user text?Correct answer: It inserts text as is, without parsing HTML - XSS is impossible
el.innerHTML = userInputparses the string as markup, and<img src=x onerror=alert(1)>runs a script.textContentshows tags as text. If you really need HTML, clean it with a sanitizer (DOMPurify).40. Why is
addEventListenerbetter thanel.onclick = handler?Correct answer: It allows multiple handlers and options (
once,passive)Reassigning
onclickoverwrites the previous handler.addEventListeneradds them independently and supports the capture phase (capture), one-time handlers and removal viasignal(AbortController). Remove handlers withremoveEventListenerand the same function.41. What does
event.preventDefault()do?Correct answer: Cancels the browser's default action (navigation, form submission)
For example, a link won't follow its
href, a form won't submit, a checkbox won't toggle. Stopping bubbling isevent.stopPropagation(); they're different things and often confused.42. What is event bubbling?
Correct answer: The event fires on the element and then rises through its ancestors up to
documentA click on a button inside a
divtriggers the button's handlers, then thediv's, then higher. Before bubbling there's the capturing phase - fromwindowdown to the target.event.targetis where the event happened,event.currentTargetis whose handler is running now.43. What is event delegation about?
Correct answer: One handler on a parent handles children's events via
event.targetInstead of 1000 handlers on every table row, there's one on
tablethat finds the target viaevent.target.closest('tr'). This saves memory and automatically works for elements added later. It relies on bubbling.44. How does
localStoragediffer fromsessionStorage?Correct answer:
localStoragepersists indefinitely,sessionStorageuntil the tab is closedBoth store strings per origin, a few megabytes in size, and aren't sent to the server (unlike cookies).
sessionStorageis also isolated per tab. Storing tokens and secrets there is unsafe: any script on the page can read them.45. What does
localStorage.getItem('n')return afterlocalStorage.setItem('n', 5)?Correct answer:
'5'Web Storage stores only strings - the value is converted with
String(). An object becomes'[object Object]', so complex data is saved withJSON.stringifyand read withJSON.parse.46. How does
DOMContentLoadeddiffer fromload?Correct answer:
DOMContentLoaded- the DOM is built;load- images and styles are loaded tooDOMContentLoadedis enough for working with the DOM (deferscripts run right before it).loadwaits for all resources, including images and iframes - you need it, for example, to measure image sizes.47. How does
Mapdiffer from a plain object?Correct answer:
Mapkeys can be any values, and insertion order is preservedObject keys are strings or symbols (the number
1becomes'1'), and there are inherited properties.Mapaccepts objects as keys, hassizeandget/set/has/delete, and is convenient for frequent additions and removals.48. How do you quickly remove duplicates from an array of primitives?
Correct answer:
[...new Set(arr)]Setstores only unique values (SameValueZero comparison). Spread turns it back into an array. Arrays of objects need a key: for example, aMapbyid.49. What does the
'use strict'directive give you?Correct answer: Strict mode: errors instead of silent failures
For example, assigning to an undeclared variable throws instead of creating a global, and
thisin a regular function isundefined, notwindow. Modules and classes run in strict mode automatically.50. How do you find the first element with the
cardclass on the page?Correct answer:
document.querySelector('.card')querySelectoraccepts any CSS selector and returns the first element ornull.querySelectorAllreturns a staticNodeListof all matches.getElementsByClassNametakes the class name without a dot, and indexing starts at 0.51. Does this code throw an error?
const user = { name: "Ann" }; user.name = "Bob";Correct answer: No -
constforbids reassignment, not object changesuser = {}would throw aTypeError, but mutating properties is allowed. To make the object itself read-only, useObject.freeze(shallowly).52. What does a template literal give you compared to string concatenation?
const msg = `Hello, ${name}! You have ${count} new messages.`;Correct answer: Embedded
${...}expressions and multi-line stringsBacktick strings evaluate any expression inside
${}. They don't escape anything, so building HTML from user input with them is still an XSS risk.53. What does
arr.length = 0do?Correct answer: Removes all elements from the array in place
Setting
lengthtruncates the array, and every reference to it sees the change.arr = []instead points the variable at a new array.54. What does
[1, 2].push(3)return?Correct answer:
3- the new array lengthpushmutates the array and returns its new length, a common source of bugs likearr = arr.push(x). For an immutable version use[...arr, x].55. How does
finddiffer fromfilter?const users = [{ id: 1 }, { id: 2 }, { id: 2 }];Correct answer:
findreturns the first match;filterreturns all matchesusers.find(u => u.id === 2)gives one object and stops early;users.filter(...)always scans the whole array.findIndexreturns the index instead.56. What is the difference between
someandevery?Correct answer:
someneeds one match;everyneeds all elements to matchBoth stop as soon as the result is known. On an empty array
somereturnsfalseandeveryreturnstrue.57. What does this code print in a classic (non-strict) script?
let s = "cat"; s[0] = "b"; console.log(s);Correct answer:
catStrings are immutable: index assignment is silently ignored (or throws in strict mode). Create a new string instead:
"b" + s.slice(1).58. What type does
(1.005).toFixed(2)return?Correct answer: A string
toFixedreturns a formatted string, soprice.toFixed(2) + 1concatenates. Also, due to binary floating point,(1.005).toFixed(2)is"1.00", not"1.01".59. What does
greet()return?function greet(name = "guest") { return `Hi, ${name}`; }Correct answer:
"Hi, guest"Default parameters apply when the argument is
undefined(missing or passed explicitly).greet(null)gives"Hi, null", becausenullis a value.60. What are
titleandyearafter this destructuring?const movie = { name: "Up" }; const { name: title, year = 2009 } = movie;Correct answer:
titleis"Up",yearis2009name: titlerenames the variable, and= 2009provides a default when the property isundefined.61. What does
[a, b] = [b, a]do?Correct answer: Swaps the values of
aandbThe right side creates a temporary array, then destructuring assigns its elements. If the previous line has no semicolon, it may be parsed as an index access - another reason to use semicolons or a linter.
62. How does
"toString" in objdiffer fromObject.hasOwn(obj, "toString")forobj = {}?Correct answer:
inistrue,Object.hasOwnisfalseinchecks the whole prototype chain.Object.hasOwn(a safer replacement forobj.hasOwnProperty) checks only the object itself.63. What does
0 && "hello"evaluate to?Correct answer:
0&&returns the first falsy operand or the last one. In JSX,{count && <Badge />}therefore renders0whencountis 0.64. Which case runs for
x = "1"?switch (x) { case 1: console.log("number"); break; case "1": console.log("string"); break; }Correct answer:
case "1"-switchcompares with===switchuses strict equality. Withoutbreak, execution falls through into the next case.65. When does a
finallyblock run?Correct answer: Always, even after a
returnor an exceptionIt is the place for cleanup such as hiding a loader or closing a connection. A
returninsidefinallyoverrides the earlier return value, so avoid it.66. How does
Number.isNaN("abc")differ fromisNaN("abc")?Correct answer:
Number.isNaNgivesfalse, globalisNaNgivestrueThe global
isNaNcoerces its argument, which leads to surprises.Number.isNaNchecks only for the actualNaNvalue.67. What does
Math.round(-2.5)return?Correct answer:
-2Math.roundrounds .5 towards +∞, soMath.round(2.5)is 3 andMath.round(-2.5)is -2. UseMath.trunc,Math.floororIntl.NumberFormatwhen you need other rules.68. What does a function return if it has no
returnstatement?Correct answer:
undefinedOnly arrow functions with a concise body (
x => x * 2) return the expression implicitly. A block bodyx => { x * 2 }returnsundefined.69. Why does
document.querySelectorAll("li").map(...)throw?Correct answer: It returns a
NodeList, which has nomapmethodA
NodeListhasforEachand is iterable, but lacks most array methods. It is also static: it doesn't update when the DOM changes.70. What does
el.classList.toggle("open")do?Correct answer: Adds the class if missing, removes it if present
A second argument forces the state:
toggle("open", isOpen). UsingclassListis safer than editing theclassNamestring by hand.71. In a click handler attached to
<ul>, how doevent.targetandevent.currentTargetdiffer?Correct answer:
targetis the clicked element;currentTargetis the<ul>This difference is the basis of event delegation: one handler on the parent inspects
event.target(often withclosest()).72. What happens with
JSON.parse("{ name: 'Ann' }")?Correct answer: It throws a
SyntaxError: JSON needs double quotesJSON is stricter than JS object literals: no single quotes, no trailing commas, no comments. Wrap parsing of untrusted data in
try/catch.73. What does
[1, [2, [3]]].flat()return?Correct answer:
[1, 2, [3]]By default
flatflattens one level. Pass a depth (flat(2)) orInfinityto flatten completely.flatMapmaps then flattens one level.74. What is a callback?
button.addEventListener("click", () => save());Correct answer: A function passed to be called later by other code
Event handlers,
setTimeoutand array methods all take callbacks. Deeply nested async callbacks ("callback hell") led to promises andasync/await.75. What does
["a", "b", "c"].at(-1)return?Correct answer:
"c"ataccepts negative indices counting from the end, a cleaner alternative toarr[arr.length - 1].arr[-1]just looks for a property named "-1".