JavaScript ES6+ Features 5 — Questions and Answers
Question 1: What does `async function` always return?
- The raw return value
- A Promise (Correct answer)
- A Generator
- An Observable
Correct answer: A Promise
An `async` function always wraps its return value in a resolved Promise, and any thrown error becomes a rejected Promise.
Question 2: Which ES2021 method replaces only the first matching substring by default and has a global-replace variant?
- String.prototype.replace()
- String.prototype.replaceAll() (Correct answer)
- String.prototype.matchAll()
- String.prototype.split()
Correct answer: String.prototype.replaceAll()
`replaceAll` replaces every occurrence of a substring without needing a global regex flag, complementing `replace` which only replaces the first match with string patterns.
Question 3: What does the optional chaining operator `?.` return when it encounters null or undefined?
- It throws a TypeError
- null
- undefined (Correct answer)
- false
Correct answer: undefined
The optional chaining operator `?.` short-circuits and returns `undefined` if the left-hand side is `null` or `undefined`.
Question 4: What is the key difference between ES6 `class` and traditional constructor functions?
- Classes support inheritance; constructor functions do not
- Class bodies are always in strict mode; constructor functions are not by default (Correct answer)
- Classes can only have static methods
- Constructor functions cannot use `new`
Correct answer: Class bodies are always in strict mode; constructor functions are not by default
Code inside a class body executes in strict mode automatically, which is not the case for regular constructor functions in non-strict scripts.
Question 5: What is `Promise.race([p1, p2])` used for?
- Running promises sequentially
- Resolving or rejecting as soon as the first promise settles (Correct answer)
- Waiting for all promises to reject
- Canceling slower promises
Correct answer: Resolving or rejecting as soon as the first promise settles
`Promise.race` resolves or rejects with the value/reason of whichever promise settles first, ignoring the rest.
Question 6: Which statement about ES6 module `import` is true?
- Imports are hoisted and bindings are live (Correct answer)
- Imports execute synchronously at the call site
- Imported bindings can be reassigned freely
- Modules are evaluated every time they are imported
Correct answer: Imports are hoisted and bindings are live
ES6 `import` bindings are hoisted to the top of the module and are live read-only views of the exported binding, not copies.
Question 7: What is the output of: `console.log(0 ?? 'default')`?
- 'default'
- 0 (Correct answer)
- null
- undefined
Correct answer: 0
The nullish coalescing operator `??` only returns the right side when the left is `null` or `undefined`; `0` is neither, so `0` is returned.
What does `async function` always return?