JavaScript Interview Questions and Answers
"What does this code output?" is one of the most common JavaScript interview questions. Here are 100 tricky ones. Guess the output, then check the answer and the short explanation. Want to be scored? Take them as a quiz.
1. Why does [33, 2, 8].sort() not sort numbers correctly?
const numbers = [33, 2, 8];
numbers.sort();
console.log(numbers[1])
- 33
- 2
- 8
- 1
Show answer
Answer: 33
Array.prototype.sort() converts numbers to strings and sorts them lexicographically by default, so [33, 2, 8] becomes [2, 33, 8]. Learn why and how to fix it.
2. Why does ('b' + 'a' + + 'a' + 'a') return "banana"?
console.log(('b' + 'a' + + 'a' + 'a').toLowerCase());
- bananaa
- baaa
- banana
- ananas
Show answer
Answer: banana
The extra + is a unary plus that turns 'a' into NaN, which is how 'b' + 'a' + + 'a' + 'a' spells 'baNaNa'. A step-by-step breakdown.
3. Why is typeof NaN "number" in JavaScript?
console.log(typeof NaN);
- NaN
- number
- null
- undefined
Show answer
Answer: number
NaN means Not-a-Number, yet typeof NaN returns "number". Here is why, according to the IEEE 754 floating point standard.
4. Why does 018 - 015 equal 5 in JavaScript?
console.log(018 - 015);
- NaN
- 3
- 5
- 13
Show answer
Answer: 5
018 is not a valid octal literal so it is read as decimal 18, while 015 is octal 13. That is why 018 - 015 equals 5 in sloppy-mode JavaScript.
5. Why is "a string" instanceof String false?
console.log("This is a string." instanceof String);
- true
- false
Show answer
Answer: false
String literals are primitives, not String objects, so "text" instanceof String returns false. Learn the difference between primitives and wrapper objects.
6. Why is 0.1 + 0.2 == 0.3 false in JavaScript?
console.log(0.1 + 0.2 == 0.3);
- true
- false
Show answer
Answer: false
0.1 + 0.2 is 0.30000000000000004 in JavaScript because of binary floating point. Why it happens and how to compare decimals safely.
7. Why does 1 + "2" + "2" return "122"?
console.log(1 + "2" + "2");
- 122
- 32
- NaN2
- NaN
Show answer
Answer: 122
The + operator switches to string concatenation as soon as one operand is a string, so 1 + "2" + "2" returns "122". Evaluated step by step.
8. Why is false == '0' true in JavaScript?
console.log(false == '0');
- false
- true
Show answer
Answer: true
false == '0' is true because loose equality converts both sides to numbers before comparing. How the abstract equality algorithm works.
9. What happens when you assign past the end of a JavaScript array?
let array = [1, 2, 3];
array[6] = 9;
console.log(array[5]);
- 1
- 2
- 9
- undefined
Show answer
Answer: undefined
Assigning array[6] on a 3-item array creates empty slots, so array[5] is undefined. How sparse arrays and length work in JavaScript.
10. What does typeof typeof 1 return?
console.log(typeof typeof 1);
- string
- number
- 1
- true
Show answer
Answer: string
typeof typeof 1 returns "string" because typeof always returns a string. How the expression is evaluated from right to left.
11. Why is 3 > 2 > 1 false in JavaScript?
console.log(3 > 2 > 1);
- true
- false
Show answer
Answer: false
3 > 2 > 1 is evaluated left to right: 3 > 2 is true, and true > 1 is false because true converts to 1. Why chained comparisons fail.
12. What does String.raw do in JavaScript?
console.log(String.raw`HelloTwitter\nworld`);
- "HelloTwitter\nworld"
- "HelloTwitter<br>world"
- "HelloTwitter world"
- "Hello Twitter world"
Show answer
Answer: "HelloTwitter\nworld"
String.raw returns the raw text of a template literal: substitutions are processed but escape sequences like \n are kept as written.
13. What do true == [] and true == ![] return?
const isTrue = true == [];
const isFalse = true == ![];
console.log(isTrue + isFalse);
- 1
- 0
- "true"
- true
Show answer
Answer: 0
true == [] and true == ![] are both false, so their sum is 0. A step-by-step walk through type coercion with arrays and booleans.
14. Why does [1, 2, 3].map(parseInt) return [1, NaN, NaN]?
console.log([1, 2, 3].map(parseInt));
- [1, 2, 3]
- [1, NaN, NaN]
- [NaN, NaN, NaN]
- [1, 1, 1]
Show answer
Answer: [1, NaN, NaN]
map passes (element, index, array) to its callback, so parseInt gets the index as the radix. That is why [1, 2, 3].map(parseInt) returns [1, NaN, NaN].
15. Why does [] + {} return "[object Object]"?
console.log([] + {});
- "[object Object]"
- 0
- "[]{}"
- NaN
Show answer
Answer: "[object Object]"
[] + {} converts both operands to primitives: '' and '[object Object]'. Their concatenation is the string "[object Object]".
16. Why is Math.max() < Math.min() true?
console.log(Math.max() < Math.min());
- false
- true
- NaN
- TypeError
Show answer
Answer: true
Math.max() with no arguments returns -Infinity and Math.min() returns Infinity, so Math.max() < Math.min() is true. Here is why.
17. What happens when you reassign a const in JavaScript?
const x = 1;
x = 2;
console.log(x);
- 1
- 2
- TypeError
- undefined
Show answer
Answer: TypeError
Reassigning a const variable throws a TypeError. Learn what const actually protects and when to use let instead.
18. Why is typeof null "object" in JavaScript?
console.log(typeof null);
- null
- object
- undefined
- number
Show answer
Answer: object
typeof null returns "object" because of a bug from the first version of JavaScript that was never fixed. How to check for null correctly.
19. What is the difference between == and === in JavaScript?
console.log(1 === "1", 1 == "1");
- true true
- false true
- false false
- true false
Show answer
Answer: false true
== converts types before comparing, === does not. That is why 1 == "1" is true but 1 === "1" is false.
20. What does Array.push() return in JavaScript?
const arr = [1, 2];
const result = arr.push(3);
console.log(result);
- [1, 2, 3]
- 3
- 2
- undefined
Show answer
Answer: 3
Array.prototype.push() returns the new length of the array, not the array itself. A common source of bugs in chained code.
21. Is a var loop variable accessible after a for loop?
for (var i = 0; i < 3; i++) {}
console.log(i);
- 2
- 3
- undefined
- ReferenceError
Show answer
Answer: 3
A var declared in a for loop is function-scoped, so it is still available after the loop ends with its final value.
22. Why does "5" * "2" equal 10 in JavaScript?
console.log("5" * "2");
- "52"
- 10
- NaN
- "10"
Show answer
Answer: 10
The * operator only works with numbers, so JavaScript converts both strings to numbers. Unlike +, it never concatenates.
23. Is an empty array truthy in JavaScript?
if ([]) {
console.log("yes");
} else {
console.log("no");
}
- yes
- no
Show answer
Answer: yes
An empty array is truthy because every object is truthy in JavaScript. Check arr.length to test whether an array is empty.
24. Is null equal to undefined in JavaScript?
console.log(null == undefined, null === undefined);
- true true
- true false
- false false
- false true
Show answer
Answer: true false
null == undefined is true, but null === undefined is false. Loose equality treats them as equal to each other and nothing else.
25. What is the difference between a++ and ++a in JavaScript?
let a = 1;
const b = a++;
console.log(a, b);
- 2 2
- 2 1
- 1 2
- 1 1
Show answer
Answer: 2 1
a++ returns the old value and then increments, ++a increments first and returns the new value.
26. What does || return in JavaScript?
console.log(0 || "default");
- 0
- default
- true
- false
Show answer
Answer: default
The || operator returns the first truthy operand, not true or false. That is why 0 || "default" returns "default".
27. What does the && operator return in JavaScript?
console.log("a" && "b");
- true
- "a"
- "b"
- false
Show answer
Answer: "b"
The && operator returns the first falsy operand, or the last operand if all are truthy. It does not always return a boolean.
28. What happens if you forget break in a JavaScript switch?
const n = 1;
switch (n) {
case 1:
console.log("one");
case 2:
console.log("two");
break;
default:
console.log("other");
}
- one
- one two
- one two other
- two
Show answer
Answer: one two
Without break, a switch case falls through and runs the next case too, until it hits a break or the end of the switch.
29. What is -7 % 3 in JavaScript?
console.log(-7 % 3);
- 2
- -1
- 1
- -2
Show answer
Answer: -1
In JavaScript, % is a remainder operator that keeps the sign of the dividend, so -7 % 3 is -1, not 2.
30. Why is "10" < "9" true in JavaScript?
console.log("10" < "9");
- true
- false
Show answer
Answer: true
Strings are compared character by character, not numerically. "1" comes before "9", so "10" < "9" is true.
31. How does a closure counter work in JavaScript?
function counter() {
let count = 0;
return () => ++count;
}
const inc = counter();
inc();
inc();
console.log(inc());
- 1
- 2
- 3
- undefined
Show answer
Answer: 3
A function returned from another function keeps access to its variables. Each call to inc() updates the same count.
32. Why does var in a loop with setTimeout print 3 3 3?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}
- 0 1 2
- 3 3 3
- 2 2 2
- undefined undefined undefined
Show answer
Answer: 3 3 3
With var, all setTimeout callbacks share one variable, which is 3 by the time they run. A classic JavaScript closure interview question.
33. Why does let in a for loop fix the setTimeout closure problem?
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}
- 0 1 2
- 3 3 3
- 2 2 2
- 0 0 0
Show answer
Answer: 0 1 2
let creates a new binding for every loop iteration, so each setTimeout callback closes over its own value of i.
34. Do two closures from the same function share state?
function make() {
let n = 0;
return () => ++n;
}
const a = make();
const b = make();
a();
a();
console.log(b());
- 3
- 1
- 2
- 0
Show answer
Answer: 1
Each call to a function creates a new scope, so closures created by separate calls have independent state.
35. Does a JavaScript closure capture the value or the variable?
let x = 1;
const getX = () => x;
x = 2;
console.log(getX());
- 1
- 2
- undefined
- ReferenceError
Show answer
Answer: 2
Closures capture variables, not values. If the variable changes later, the closure sees the new value.
36. How do closures create private variables in JavaScript?
const counter = (function () {
let count = 0;
return { inc: () => ++count };
})();
counter.inc();
console.log(counter.count);
- 1
- 0
- undefined
- ReferenceError
Show answer
Answer: undefined
Variables inside an IIFE are only reachable through the functions it returns. That makes count private and counter.count undefined.
37. How do you write a once() function with a closure?
function once(fn) {
let done = false;
return (...args) => {
if (done) return;
done = true;
return fn(...args);
};
}
const hello = once(() => "hi");
console.log(hello(), hello());
- hi undefined
- hi hi
- undefined undefined
- hi
Show answer
Answer: hi undefined
A once() helper uses a closure flag to run a function only on the first call. Later calls return undefined.
38. Why does using a var before its declaration return undefined?
console.log(a);
var a = 5;
- 5
- undefined
- ReferenceError
- null
Show answer
Answer: undefined
var declarations are hoisted to the top of their scope and initialized with undefined. Only the assignment stays in place.
39. What is the temporal dead zone in JavaScript?
console.log(b);
let b = 5;
- 5
- undefined
- ReferenceError
- null
Show answer
Answer: ReferenceError
let and const are hoisted but not initialized. Accessing them before the declaration throws a ReferenceError: the temporal dead zone.
40. Can you call a function before it is declared in JavaScript?
console.log(greet());
function greet() {
return "hi";
}
- hi
- undefined
- TypeError
- ReferenceError
Show answer
Answer: hi
Function declarations are hoisted with their body, so you can call them before the line where they are defined.
41. Why can't you call a function expression before it's defined?
console.log(greet());
var greet = function () {
return "hi";
};
- hi
- undefined
- TypeError
- ReferenceError
Show answer
Answer: TypeError
Only the var is hoisted, not the function assigned to it. Calling it early means calling undefined, which throws a TypeError.
42. Does let have block scope in JavaScript?
let x = 1;
{
let x = 2;
}
console.log(x);
- 1
- 2
- undefined
- SyntaxError
Show answer
Answer: 1
let is block-scoped, so a let inside { } creates a separate variable that does not affect the outer one.
43. Does var have block scope in JavaScript?
var y = 1;
if (true) {
var y = 2;
}
console.log(y);
- 1
- 2
- undefined
- SyntaxError
Show answer
Answer: 2
var ignores block scope, so declaring it again inside an if block overwrites the outer variable.
44. Why does a var inside a function shadow the outer variable?
var x = 1;
function f() {
console.log(x);
var x = 2;
}
f();
- 1
- 2
- undefined
- ReferenceError
Show answer
Answer: undefined
A var declared inside a function is hoisted to the top of that function and shadows the outer variable, even before its line runs.
45. What happens when you assign a variable without declaring it?
function f() {
y = 10;
}
f();
console.log(y);
- 10
- undefined
- ReferenceError
Show answer
Answer: 10
Assigning to an undeclared variable creates a global in sloppy mode. In strict mode it throws a ReferenceError.
46. Why doesn't typeof throw for undeclared variables?
console.log(typeof notDeclared);
- undefined
- ReferenceError
- null
- object
Show answer
Answer: undefined
typeof returns "undefined" for a variable that was never declared instead of throwing a ReferenceError.
47. Why does this become undefined when you extract a method?
class User {
name = "Ana";
getName() {
return this.name;
}
}
const getName = new User().getName;
console.log(getName());
- Ana
- undefined
- TypeError
- ""
Show answer
Answer: TypeError
this depends on how a function is called. A method called without its object has no this, so reading a property throws.
48. Why does an arrow function method return undefined for this?
const obj = {
value: 42,
regular() {
return this.value;
},
arrow: () => this.value,
};
console.log(obj.regular(), obj.arrow());
- 42 42
- 42 undefined
- undefined 42
- TypeError
Show answer
Answer: 42 undefined
Arrow functions don't have their own this. An arrow function used as an object method takes this from the outer scope, not the object.
49. Can you change this on a bound function with call()?
function greet() {
return this.name;
}
const bound = greet.bind({ name: "Ana" });
console.log(bound.call({ name: "Bob" }));
- Ana
- Bob
- undefined
- TypeError
Show answer
Answer: Ana
A function returned by bind() has a fixed this. Calling it with call() or apply() cannot change it.
50. Why does an arrow function in setTimeout keep this?
const timer = {
seconds: 10,
start() {
setTimeout(() => console.log(this.seconds));
},
};
timer.start();
- 10
- undefined
- TypeError
Show answer
Answer: 10
An arrow function inside a method inherits this from the method, so this.seconds still works inside setTimeout.
51. What is the difference between call and apply in JavaScript?
function sum(a, b) {
return this.base + a + b;
}
console.log(sum.apply({ base: 1 }, [2, 3]));
- 6
- "123"
- NaN
- 5
Show answer
Answer: 6
call() and apply() both set this. call takes arguments one by one, apply takes them as an array.
52. What happens when a constructor returns an object?
function Person(name) {
this.name = name;
return { name: "Other" };
}
console.log(new Person("Ana").name);
- Ana
- Other
- undefined
- TypeError
Show answer
Answer: Other
If a constructor returns an object, new gives you that object instead of this. Returning a primitive is ignored.
53. Can call() change this in an arrow function?
const getX = () => this.x;
console.log(getX.call({ x: 1 }));
- 1
- undefined
- TypeError
- null
Show answer
Answer: undefined
Arrow functions ignore the this passed to call(), apply() and bind(). They always use this from where they're defined.
54. Why does a Promise run before setTimeout 0?
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
- A B C D
- A C D B
- A D C B
- A D B C
Show answer
Answer: A D C B
Promise callbacks are microtasks and run before timers. That is why the order is A D C B. A classic event loop interview question.
55. What does an async function return in JavaScript?
async function f() {
return 1;
}
console.log(f() instanceof Promise);
- true
- false
Show answer
Answer: true
An async function always returns a Promise. A plain return value is wrapped in a resolved Promise.
56. What runs first after await in JavaScript?
async function run() {
console.log(1);
await null;
console.log(2);
}
run();
console.log(3);
- 1 2 3
- 1 3 2
- 3 1 2
- 1 3
Show answer
Answer: 1 3 2
await pauses the async function and lets the rest of the synchronous code run first. The code after await runs as a microtask.
57. Is the Promise constructor callback synchronous?
new Promise((resolve) => {
console.log("A");
resolve();
}).then(() => console.log("B"));
console.log("C");
- C A B
- A C B
- A B C
- C B A
Show answer
Answer: A C B
The function passed to new Promise runs immediately and synchronously. Only the .then() callbacks are asynchronous.
58. What happens when one promise in Promise.all rejects?
Promise.all([
Promise.resolve(1),
Promise.reject(new Error("fail")),
Promise.resolve(3),
])
.then((values) => console.log(values))
.catch((err) => console.log(err.message));
- [1, 3]
- fail
- [1, undefined, 3]
- 1 fail 3
Show answer
Answer: fail
Promise.all rejects as soon as any promise rejects, and the results of the others are lost. Use Promise.allSettled to keep them.
59. What is the difference between Promise.all and Promise.allSettled?
Promise.allSettled([Promise.resolve(1), Promise.reject(2)])
.then((results) => console.log(results.map((r) => r.status)));
- ["fulfilled", "rejected"]
- [1, 2]
- ["fulfilled", "fulfilled"]
- Uncaught 2
Show answer
Answer: ["fulfilled", "rejected"]
Promise.allSettled never rejects. It waits for every promise and returns an object with a status for each one.
60. Why does a .then() without return pass undefined?
Promise.resolve(1)
.then((x) => x + 1)
.then((x) => {
x * 2;
})
.then((x) => console.log(x));
- 4
- 2
- undefined
- NaN
Show answer
Answer: undefined
Each .then() passes its return value to the next one. A callback with a block body and no return passes undefined.
61. What happens if you call resolve twice in a Promise?
new Promise((resolve) => {
resolve("first");
resolve("second");
}).then(console.log);
- first
- second
- first second
- Error
Show answer
Answer: first
A promise can only settle once. Later calls to resolve or reject are silently ignored.
62. In what order do setTimeout callbacks run?
setTimeout(() => console.log("A"), 100);
setTimeout(() => console.log("B"), 0);
setTimeout(() => console.log("C"), 10);
- A B C
- B C A
- B A C
- C B A
Show answer
Answer: B C A
Timers run by delay, not by the order they were created, so a 0 ms timer runs before a 10 ms and a 100 ms timer.
63. What is queueMicrotask in JavaScript?
setTimeout(() => console.log("timeout"));
queueMicrotask(() => console.log("microtask"));
console.log("sync");
- timeout microtask sync
- sync microtask timeout
- sync timeout microtask
- microtask sync timeout
Show answer
Answer: sync microtask timeout
queueMicrotask schedules a callback in the microtask queue, so it runs after synchronous code but before any setTimeout.
64. Why doesn't try/catch catch an error from an async function?
async function fail() {
throw new Error("oops");
}
try {
fail();
console.log("no error");
} catch (e) {
console.log("caught");
}
- no error
- caught
- oops
- nothing
Show answer
Answer: no error
An async function turns thrown errors into a rejected promise. Without await, try/catch never sees the error.
65. Why do object keys 1 and "1" overwrite each other?
const obj = {};
obj[1] = "a";
obj["1"] = "b";
console.log(obj[1]);
- a
- b
- undefined
- ["a", "b"]
Show answer
Answer: b
Object property keys are always strings (or symbols), so the number 1 is converted to "1" and both refer to the same property.
66. What happens when you use an object as an object key?
const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
- 123
- 456
- undefined
- TypeError
Show answer
Answer: 456
Objects used as keys are converted to the string "[object Object]", so different objects end up as the same key.
67. Why is {} === {} false in JavaScript?
console.log({} === {});
- true
- false
Show answer
Answer: false
Objects are compared by reference, not by content. Two separately created empty objects are never equal.
68. Are JavaScript objects copied by reference?
const a = { n: 1 };
const b = a;
b.n = 2;
console.log(a.n);
- 1
- 2
- undefined
- TypeError
Show answer
Answer: 2
Assigning an object to another variable copies the reference, not the object. Changing one changes both.
69. Does the spread operator make a deep copy?
const a = { n: 1, inner: { m: 1 } };
const b = { ...a };
b.n = 2;
b.inner.m = 2;
console.log(a.n, a.inner.m);
- 1 1
- 1 2
- 2 2
- 2 1
Show answer
Answer: 1 2
Object spread creates a shallow copy. Top-level values are copied, but nested objects are still shared.
70. Is Object.freeze deep or shallow?
const obj = Object.freeze({ a: 1, inner: { b: 1 } });
obj.a = 2;
obj.inner.b = 2;
console.log(obj.a, obj.inner.b);
- 2 2
- 1 1
- 1 2
- TypeError
Show answer
Answer: 1 2
Object.freeze only freezes the top level. Nested objects can still be changed.
71. In what order does Object.keys return keys?
const obj = { b: 1, 2: "x", a: 2, 1: "y" };
console.log(Object.keys(obj));
- ["b", "2", "a", "1"]
- ["1", "2", "b", "a"]
- ["a", "b", "1", "2"]
- ["1", "2", "a", "b"]
Show answer
Answer: ["1", "2", "b", "a"]
Integer-like keys come first in ascending order, then string keys in insertion order.
72. Why does JSON.stringify drop undefined and functions?
console.log(JSON.stringify({ a: undefined, b: null, c: () => 1 }));
- {"a":null,"b":null,"c":null}
- {"b":null}
- {"a":undefined,"b":null}
- {}
Show answer
Answer: {"b":null}
JSON has no undefined or function type, so JSON.stringify skips those properties. null is kept.
73. When do default parameters apply in JavaScript?
function f(x = 10) {
return x;
}
console.log(f(undefined), f(null));
- 10 10
- 10 null
- undefined null
- null null
Show answer
Answer: 10 null
Default parameters only apply when the argument is undefined. Passing null keeps null.
74. What does function.length return in JavaScript?
function f(a, b = 2, c) {}
console.log(f.length);
- 3
- 2
- 1
- 0
Show answer
Answer: 1
function.length counts parameters before the first one with a default value. Rest parameters are not counted.
75. Is a named function expression's name available outside?
const f = function g() {
return typeof g;
};
console.log(f(), typeof g);
- function undefined
- function function
- undefined undefined
- ReferenceError
Show answer
Answer: function undefined
The name of a named function expression is only visible inside the function itself, not in the outer scope.
76. Why does a return on its own line return undefined?
function get() {
return
42;
}
console.log(get());
- 42
- undefined
- SyntaxError
- null
Show answer
Answer: undefined
Automatic semicolon insertion adds a semicolon right after return, so the value on the next line is never returned.
77. What happens when you declare the same function twice?
function f() {
return 1;
}
function f() {
return 2;
}
console.log(f());
- 1
- 2
- SyntaxError
- undefined
Show answer
Answer: 2
With duplicate function declarations, the last one wins because both are hoisted and the second overwrites the first.
78. What happens when you call a function with missing arguments?
function add(a, b) {
return a + b;
}
console.log(add(1));
- 1
- NaN
- undefined
- TypeError
Show answer
Answer: NaN
Missing arguments are undefined. Adding a number to undefined gives NaN.
79. Do objects see prototype changes made after they're created?
function Dog() {}
Dog.prototype.bark = () => "woof";
const d = new Dog();
Dog.prototype.bark = () => "WOOF";
console.log(d.bark());
- woof
- WOOF
- undefined
- TypeError
Show answer
Answer: WOOF
Objects look up methods on their prototype at call time, so changes to the prototype affect existing objects too.
80. Are JavaScript classes hoisted?
const p = new Person();
class Person {}
- Person {}
- undefined
- TypeError
- ReferenceError
Show answer
Answer: ReferenceError
Class declarations are hoisted like let: they exist in a temporal dead zone, so using them early throws a ReferenceError.
81. Can you call a static method on a class instance?
class Counter {
static create() {
return new Counter();
}
}
const c = Counter.create();
console.log(typeof c.create);
- function
- undefined
- object
- TypeError
Show answer
Answer: undefined
Static methods live on the class itself, not on instances, so instance.staticMethod is undefined.
82. What is the difference between in and hasOwnProperty?
const parent = { a: 1 };
const child = Object.create(parent);
console.log("a" in child, child.hasOwnProperty("a"));
- true true
- true false
- false false
- false true
Show answer
Answer: true false
The in operator checks the whole prototype chain. hasOwnProperty only checks the object itself.
83. What is typeof a class in JavaScript?
class A {}
console.log(typeof A);
- class
- object
- function
- undefined
Show answer
Answer: function
typeof a class returns "function" because classes are special constructor functions under the hood.
84. What happens when you assign to a getter-only property?
class Account {
#balance = 100;
get balance() {
return this.#balance;
}
}
const acc = new Account();
acc.balance = 500;
console.log(acc.balance);
- 500
- 100
- undefined
- SyntaxError
Show answer
Answer: 100
Assigning to a property that only has a getter is silently ignored in sloppy mode and throws a TypeError in strict mode.
85. What is the difference between ?? and || in JavaScript?
console.log(0 ?? 5, 0 || 5);
- 5 5
- 0 5
- 0 0
- 5 0
Show answer
Answer: 0 5
?? only falls back for null and undefined. || falls back for any falsy value, including 0 and "".
86. How does optional chaining short-circuit in JavaScript?
const user = {};
console.log(user.profile?.name.first);
- undefined
- TypeError
- null
- ""
Show answer
Answer: undefined
When ?. hits null or undefined, the whole rest of the chain is skipped and the result is undefined, with no TypeError.
87. When do destructuring default values apply?
const { a = 1, b = 2 } = { a: null, b: undefined };
console.log(a, b);
- 1 2
- null 2
- null undefined
- 1 undefined
Show answer
Answer: null 2
Destructuring defaults only apply when the value is undefined. A null value is kept.
88. How do you swap two variables with destructuring?
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);
- 1 2
- 2 1
- 2 2
- SyntaxError
Show answer
Answer: 2 1
Array destructuring swaps two variables in one line without a temporary variable: [a, b] = [b, a].
89. How do you remove duplicates from an array with Set?
console.log([...new Set([1, 1, 2, 3, 3])]);
- [1, 1, 2, 3, 3]
- [1, 2, 3]
- Set {1, 2, 3}
- [2]
Show answer
Answer: [1, 2, 3]
A Set only stores unique values. Spreading it back into an array is the shortest way to remove duplicates.
90. What does the rest operator do in object destructuring?
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(rest);
- [2, 3]
- { b: 2, c: 3 }
- { a: 1, b: 2, c: 3 }
- SyntaxError
Show answer
Answer: { b: 2, c: 3 }
Object rest collects all remaining properties into a new object, which is handy for removing a key without mutation.
91. Why can a Map have both 1 and "1" as keys?
const map = new Map();
map.set(1, "number");
map.set("1", "string");
console.log(map.size);
- 1
- 2
- 0
- undefined
Show answer
Answer: 2
A Map keeps keys with their original type, so 1 and "1" are different keys, unlike in a plain object.
92. What does Array.from({ length: 3 }) create?
console.log(Array.from({ length: 3 }, (_, i) => i * 2));
- [0, 2, 4]
- [3, 6, 9]
- [0, 1, 2]
- [undefined, undefined, undefined]
Show answer
Answer: [0, 2, 4]
Array.from with a length object and a map function is a quick way to generate arrays of computed values.
93. Why is [1, 2, 3] == "1,2,3" true?
console.log([1, 2, 3] == "1,2,3");
- true
- false
Show answer
Answer: true
Loose equality converts the array to a primitive with toString(), which joins items with commas.
94. Why does indexOf not find NaN but includes does?
console.log([NaN].indexOf(NaN), [NaN].includes(NaN));
- 0 true
- -1 true
- -1 false
- 0 false
Show answer
Answer: -1 true
indexOf uses strict equality, and NaN === NaN is false. includes uses SameValueZero, which treats NaN as equal to itself.
95. What happens when you set an array's length?
const arr = [1, 2, 3, 4];
arr.length = 2;
console.log(arr);
- [1, 2, 3, 4]
- [1, 2]
- [3, 4]
- TypeError
Show answer
Answer: [1, 2]
Setting array.length to a smaller number truncates the array and deletes the items past the new length.
96. Why does reduce throw on an empty array?
console.log([].reduce((a, b) => a + b));
- 0
- undefined
- NaN
- TypeError
Show answer
Answer: TypeError
reduce without an initial value has nothing to start with on an empty array, so it throws a TypeError.
97. Can you push to a const array in JavaScript?
const arr = [1];
arr.push(2);
console.log(arr);
- [1, 2]
- [1]
- TypeError
- [2]
Show answer
Answer: [1, 2]
const prevents reassigning the variable, not changing the array. push() works on a const array.
98. Can you change a character in a JavaScript string?
const str = "hello";
str[0] = "H";
console.log(str);
- Hello
- hello
- TypeError
- Hhello
Show answer
Answer: hello
Strings are immutable, so assigning to str[0] does nothing. Create a new string instead.
99. Why does replace() only change the first match?
console.log("a-b-c".replace("-", "+"));
- a+b+c
- a+b-c
- a-b+c
- a-b-c
Show answer
Answer: a+b-c
String.replace with a string pattern only replaces the first occurrence. Use replaceAll or a global regex for all of them.
100. What is the difference between parseInt and Number?
console.log(parseInt("08.9px"), Number("08.9px"));
- 8.9 8.9
- 8 NaN
- NaN NaN
- 8 8.9
Show answer
Answer: 8 NaN
parseInt reads digits until it hits an invalid character. Number converts the whole string or returns NaN.
Practice by topic
Prefer a scored round? Take the JavaScript quiz, or practice one area at a time:
- JavaScript Basics Quiz for Beginners
- JavaScript Type Coercion Quiz
- JavaScript Closures Quiz
- JavaScript Scope and Hoisting Quiz
- JavaScript this Keyword Quiz
- JavaScript Promises and Async/Await Quiz
- JavaScript Objects Quiz
- JavaScript Arrays Quiz
- JavaScript Functions Quiz
- JavaScript Classes and Prototypes Quiz
- JavaScript ES6+ Quiz
- JavaScript Strings Quiz
- JavaScript Numbers Quiz
- JavaScript typeof and Types Quiz