JavaScript quiz – 44 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (15 questions)
How do you print something to the console in JavaScript?
- print("Hi")
- console.log("Hi")
- echo("Hi")
- System.out.println("Hi")
Show answer
Correct: console.log("Hi")
console.log() is the standard function for console output.
What does this code print?
console.log(typeof "5", typeof 5);- string number
- number number
- string string
- number string
Show answer
Correct: string number
Text in quotation marks is a string, 5 is a number.
Which keyword do you use to declare a variable that cannot be reassigned?
- var
- let
- const
- static
Show answer
Correct: const
const prevents reassignment. The contents of objects and arrays remain mutable, though.
What does this code print?
console.log("5" + 3);- 8
- 53
- 15
- NaN
Show answer
Correct: 53
As soon as one operand is a string, + concatenates – the result is the text "53".
What does this code print?
console.log("5" - 3);- 53
- 2
- NaN
- Error
Show answer
Correct: 2
- exists only for numbers, so "5" is converted to the number 5: 2.
What does 5 === "5" evaluate to?
- true
- false
- undefined
- Error
Show answer
Correct: false
=== compares without type conversion – number and string are different. (5 == "5" would be true.)
What does typeof null return?
- "null"
- "undefined"
- "object"
- "number"
Show answer
Correct: "object"
A well-known historical mistake: typeof null is "object". Check for null with === null.
What value does x have at the end?
let x = 5;
x *= 2;
x -= 1;
console.log(x);- 10
- 9
- 8
- 7
Show answer
Correct: 9
x *= 2 gives 10, then x -= 1 gives 9.
Which loop iterates over the values of an array arr?
- for (const x in arr)
- for (const x of arr)
- for x : arr
- foreach x in arr
Show answer
Correct: for (const x of arr)
for...of yields the values, whereas for...in yields the indices as strings.
What does this code print?
const l = [1, 2, 3];
console.log(l.length, l[1]);- 3 2
- 2 3
- 3 1
- 2 2
Show answer
Correct: 3 2
The array has three elements, and index 1 is the second element: 2.
What does this code print?
const f = x => x * 2;
console.log(f(4));- 4
- 8
- undefined
- x * 2
Show answer
Correct: 8
The arrow function automatically returns its expression: 4 * 2 = 8.
What does this code print?
console.log(Boolean([]), Boolean(""));- false false
- true false
- true true
- false true
Show answer
Correct: true false
An empty array is truthy (unlike in Python), an empty string is falsy.
What does 7 / 2 evaluate to in JavaScript?
- 3
- 3.5
- 4
- 3.0
Show answer
Correct: 3.5
JavaScript has only one number type; / always returns the exact result. For integer division use Math.floor(7 / 2).
What value does a variable that has not been assigned anything (let y;) have?
- null
- 0
- undefined
- ""
Show answer
Correct: undefined
Uninitialized variables have the value undefined. null is a deliberately set "empty" value.
What does filter do on arrays?
- Modifies the original and returns nothing
- Returns a new array with the matching elements
- Returns only the first matching element
- Returns true or false
Show answer
Correct: Returns a new array with the matching elements
filter keeps all elements for which the function returns true and leaves the original unchanged.
Intermediate (15 questions)
What does this code print?
console.log([1, 2, 3].map(x => x * 2));- [1, 2, 3]
- [2, 4, 6]
- 6
- [2, 4]
Show answer
Correct: [2, 4, 6]
map applies the function to every element and returns a new array: [2, 4, 6].
What does this code print?
console.log([10, 9, 1].sort());- [1, 9, 10]
- [1, 10, 9]
- [10, 9, 1]
- [9, 10, 1]
Show answer
Correct: [1, 10, 9]
Without a compare function, sort sorts as text: "1" < "10" < "9". For numbers you need (a, b) => a - b.
What does this code print?
const { a, b = 5 } = { a: 1 };
console.log(a, b);- 1 undefined
- 1 5
- undefined 5
- Error
Show answer
Correct: 1 5
b is missing in the object, so the default value 5 applies.
What does this code print?
console.log(0 || 10, 0 ?? 10);- 10 10
- 10 0
- 0 10
- 0 0
Show answer
Correct: 10 0
|| replaces any falsy value (including 0), ?? only null/undefined.
What does this code print?
const user = {};
console.log(user.profil?.name);- TypeError
- undefined
- null
- ""
Show answer
Correct: undefined
?. stops as soon as user.profil is undefined and returns undefined instead of an error.
What length does a have at the end?
const a = [1, 2];
const b = a;
b.push(3);
console.log(a.length);- 2
- 3
- 1
- Error
Show answer
Correct: 3
b = a copies only the reference – both names point to the same array.
What does this code print?
console.log(JSON.stringify({ a: 1, b: undefined, c: [1] }));- {"a":1,"b":undefined,"c":[1]}
- {"a":1,"c":[1]}
- {"a":1,"b":null,"c":[1]}
- Error
Show answer
Correct: {"a":1,"c":[1]}
undefined values (and functions) are omitted during serialization; in arrays they would become null.
What does this code print?
console.log(typeof NaN, NaN === NaN);- NaN true
- number false
- number true
- undefined false
Show answer
Correct: number false
NaN is of type number and not equal to itself. Check with Number.isNaN(x).
What does ... do in [...a, ...b]?
- Unpacks the elements of both arrays into a new array
- Multiplies the arrays
- Comments out code
- Defines rest parameters
Show answer
Correct: Unpacks the elements of both arrays into a new array
The spread operator unpacks iterable values. In function parameters (function f(...args)), however, ... means rest.
Which error type does null.x throw?
- ReferenceError
- TypeError
- SyntaxError
- RangeError
Show answer
Correct: TypeError
Accessing a property of null or undefined results in a TypeError. A ReferenceError occurs for undeclared variables.
What does this code print?
const n = 3;
console.log(`n is ${n * 2}`);- n is 3
- n is 6
- n is ${n * 2}
- Error
Show answer
Correct: n is 6
Inside ${...} in a template literal you can put any expression: 3 * 2 gives 6.
What is the difference between var and let?
- No difference
varis function-scoped,letis block-scopedletis only for numbersvaris faster
Show answer
Correct: var is function-scoped, let is block-scoped
let (and const) are limited to the block { }; var applies throughout the function and is hoisted – a source of many bugs.
What does this code print?
console.log([1, 2, 3].reduce((s, x) => s + x, 0));- 0
- 6
- [1, 2, 3]
- 123
Show answer
Correct: 6
reduce starts at 0 and adds 1, 2, 3 one after another: 6.
What is the # in class A { #x = 1; } for?
- It comments out the field
- It makes
xa private field, accessible only inside the class - It makes
xstatic - It makes
xconstant
Show answer
Correct: It makes x a private field, accessible only inside the class
Fields and methods declared with # are truly private – access from outside is a syntax error.
What does this code print?
try {
JSON.parse("{");
} catch (e) {
console.log(e.name);
} finally {
console.log("done");
}- SyntaxError, then done
- done, then SyntaxError
- only SyntaxError
- only done
Show answer
Correct: SyntaxError, then done
JSON.parse throws a SyntaxError, which is caught; finally always runs afterwards.
Advanced (14 questions)
What does this code print?
function z() {
let n = 0;
return () => ++n;
}
const a = z(), b = z();
console.log(a(), a(), b());- 1 1 1
- 1 2 1
- 1 2 3
- 1 2 2
Show answer
Correct: 1 2 1
Each call of z() creates its own closure with its own n. a counts 1, 2; b starts at 1.
What output is produced?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}- 0 1 2
- 3 3 3
- 2 2 2
- 0 0 0
Show answer
Correct: 3 3 3
var is function-scoped: all callbacks share the same i, which is 3 after the loop. With let you would get 0 1 2.
In which order is the output printed?
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");- A B C D
- A D B C
- A D C B
- A C D B
Show answer
Correct: A D C B
First the synchronous code (A, D), then microtasks/promises (C), then macrotasks/timers (B).
What does an async function always return?
- The return value directly
- A promise
- An array
undefined
Show answer
Correct: A promise
async functions always return a promise, which is fulfilled with the return value or rejected on an exception.
What happens with Promise.all([p1, p2]) if p2 is rejected?
- It waits for
p1and then returns both results - The result promise is rejected immediately with the error
- The error is ignored
- The program crashes immediately
Show answer
Correct: The result promise is rejected immediately with the error
Promise.all fails at the first rejection. If you need all results, use Promise.allSettled.
What is special about this in arrow functions?
- It is always
window - They have no
thisof their own and take it from the surrounding environment - It is always
undefined - It points to the function itself
Show answer
Correct: They have no this of their own and take it from the surrounding environment
In arrow functions this is lexically bound – ideal for callbacks in classes, unsuitable as an object method with its own this.
What happens here when f() is called?
class Z {
n = 0;
inc() { this.n++; }
}
const f = new Z().inc;
f();nbecomes 1- TypeError, because
thisis undefined nbecomes NaN- Nothing happens
Show answer
Correct: TypeError, because this is undefined
The method has been detached from the object; in classes (strict mode) this is then undefined. Fix: bind or an arrow function as a class field.
What is a generator?
- A function with
function*that delivers values one at a time withyieldand pauses - A tool that generates code
- A kind of promise
- A class for random numbers
Show answer
Correct: A function with function* that delivers values one at a time with yield and pauses
Generators deliver values on demand (lazily) and keep their state in between – ideal for large or endless sequences.
What does this code print?
console.log([..."abc"].map((c, i) => c + i).join("-"));- a0-b1-c2
- abc-012
- a-b-c
- 0a-1b-2c
Show answer
Correct: a0-b1-c2
The string is split into characters; map appends the index to each character; join("-") joins them: a0-b1-c2.
What advantage does Map have over a plain object?
- Keys can be of any type, and insertion order and
sizeare guaranteed - Map is always faster
- Map can store JSON
- Map has no methods
Show answer
Correct: Keys can be of any type, and insertion order and size are guaranteed
With Map, objects or numbers can also be keys; in addition there are no collisions with inherited properties like toString.
What is a WeakMap for?
- It stores only small values
- Its object keys are weakly referenced and can be removed by the garbage collector
- It is a read-only Map
- It is a Map without order
Show answer
Correct: Its object keys are weakly referenced and can be removed by the garbage collector
Ideal for attaching extra data to objects (e.g. caches) without causing memory leaks – the entry disappears together with the object.
What does this code print?
const o = Object.freeze({ a: { b: 1 } });
o.a.b = 2;
console.log(o.a.b);- 1
- 2
- TypeError
- undefined
Show answer
Correct: 2
Object.freeze works only shallowly: the nested object remains mutable.
Which syntax belongs to ES modules?
- const x = require("x")
- import x from "x"
- include "x"
- using x
Show answer
Correct: import x from "x"
import/export is the standard module syntax; require belongs to the older CommonJS system of Node.js.
What is event delegation?
- A handler on the parent element serves the events of many children via
event.target - An event is sent to another browser
- Events are delayed automatically
- A handler is removed after the first click
Show answer
Correct: A handler on the parent element serves the events of many children via event.target
Because events in the DOM "bubble" upward, one listener on the container is enough – even for elements added later.