JSJavaScript

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?

  1. print("Hi")
  2. console.log("Hi")
  3. echo("Hi")
  4. 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);
  1. string number
  2. number number
  3. string string
  4. 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?

  1. var
  2. let
  3. const
  4. 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);
  1. 8
  2. 53
  3. 15
  4. 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);
  1. 53
  2. 2
  3. NaN
  4. Error
Show answer

Correct: 2

- exists only for numbers, so "5" is converted to the number 5: 2.

What does 5 === "5" evaluate to?

  1. true
  2. false
  3. undefined
  4. Error
Show answer

Correct: false

=== compares without type conversion – number and string are different. (5 == "5" would be true.)

What does typeof null return?

  1. "null"
  2. "undefined"
  3. "object"
  4. "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);
  1. 10
  2. 9
  3. 8
  4. 7
Show answer

Correct: 9

x *= 2 gives 10, then x -= 1 gives 9.

Which loop iterates over the values of an array arr?

  1. for (const x in arr)
  2. for (const x of arr)
  3. for x : arr
  4. 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]);
  1. 3 2
  2. 2 3
  3. 3 1
  4. 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));
  1. 4
  2. 8
  3. undefined
  4. 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(""));
  1. false false
  2. true false
  3. true true
  4. 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?

  1. 3
  2. 3.5
  3. 4
  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?

  1. null
  2. 0
  3. undefined
  4. ""
Show answer

Correct: undefined

Uninitialized variables have the value undefined. null is a deliberately set "empty" value.

What does filter do on arrays?

  1. Modifies the original and returns nothing
  2. Returns a new array with the matching elements
  3. Returns only the first matching element
  4. 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. [1, 2, 3]
  2. [2, 4, 6]
  3. 6
  4. [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. [1, 9, 10]
  2. [1, 10, 9]
  3. [10, 9, 1]
  4. [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. 1 undefined
  2. 1 5
  3. undefined 5
  4. 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);
  1. 10 10
  2. 10 0
  3. 0 10
  4. 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);
  1. TypeError
  2. undefined
  3. null
  4. ""
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);
  1. 2
  2. 3
  3. 1
  4. 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] }));
  1. {"a":1,"b":undefined,"c":[1]}
  2. {"a":1,"c":[1]}
  3. {"a":1,"b":null,"c":[1]}
  4. 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);
  1. NaN true
  2. number false
  3. number true
  4. 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]?

  1. Unpacks the elements of both arrays into a new array
  2. Multiplies the arrays
  3. Comments out code
  4. 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?

  1. ReferenceError
  2. TypeError
  3. SyntaxError
  4. 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}`);
  1. n is 3
  2. n is 6
  3. n is ${n * 2}
  4. 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?

  1. No difference
  2. var is function-scoped, let is block-scoped
  3. let is only for numbers
  4. var is 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));
  1. 0
  2. 6
  3. [1, 2, 3]
  4. 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?

  1. It comments out the field
  2. It makes x a private field, accessible only inside the class
  3. It makes x static
  4. It makes x constant
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");
}
  1. SyntaxError, then done
  2. done, then SyntaxError
  3. only SyntaxError
  4. 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 2 1
  3. 1 2 3
  4. 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);
}
  1. 0 1 2
  2. 3 3 3
  3. 2 2 2
  4. 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");
  1. A B C D
  2. A D B C
  3. A D C B
  4. 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?

  1. The return value directly
  2. A promise
  3. An array
  4. 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?

  1. It waits for p1 and then returns both results
  2. The result promise is rejected immediately with the error
  3. The error is ignored
  4. 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?

  1. It is always window
  2. They have no this of their own and take it from the surrounding environment
  3. It is always undefined
  4. 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();
  1. n becomes 1
  2. TypeError, because this is undefined
  3. n becomes NaN
  4. 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?

  1. A function with function* that delivers values one at a time with yield and pauses
  2. A tool that generates code
  3. A kind of promise
  4. 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("-"));
  1. a0-b1-c2
  2. abc-012
  3. a-b-c
  4. 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?

  1. Keys can be of any type, and insertion order and size are guaranteed
  2. Map is always faster
  3. Map can store JSON
  4. 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?

  1. It stores only small values
  2. Its object keys are weakly referenced and can be removed by the garbage collector
  3. It is a read-only Map
  4. 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. 1
  2. 2
  3. TypeError
  4. undefined
Show answer

Correct: 2

Object.freeze works only shallowly: the nested object remains mutable.

Which syntax belongs to ES modules?

  1. const x = require("x")
  2. import x from "x"
  3. include "x"
  4. 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?

  1. A handler on the parent element serves the events of many children via event.target
  2. An event is sent to another browser
  3. Events are delayed automatically
  4. 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.