JavaScript ES6+ Features 3 — Questions and Answers
Question 1: What is the result of `[...'hello']`?
- ['hello']
- ['h','e','l','l','o'] (Correct answer)
- ['h e l l o']
- Error
Correct answer: ['h','e','l','l','o']
The spread operator on a string iterates over each character, producing an array of individual characters.
Question 2: Which statement correctly creates a class with a static method in ES6?
- class Foo { static bar() {} } (Correct answer)
- class Foo { Foo.bar() {} }
- class Foo { method bar() {} }
- class Foo { @static bar() {} }
Correct answer: class Foo { static bar() {} }
The `static` keyword before a method definition in a class body creates a method on the class itself, not on instances.
Question 3: What does `Promise.allSettled([p1, p2])` return when `p1` resolves and `p2` rejects?
- Rejects immediately with p2's reason
- Resolves with only p1's value
- Resolves with an array of {status, value/reason} for both (Correct answer)
- Throws a TypeError
Correct answer: Resolves with an array of {status, value/reason} for both
`Promise.allSettled` always resolves with an array describing each promise's outcome—fulfilled or rejected—never short-circuits.
Question 4: In ES6 template literals, how do you embed a JavaScript expression?
- ${expression} (Correct answer)
- {{expression}}
- #{expression}
- <%=expression%>
Correct answer: ${expression}
Template literals use `${expression}` syntax inside backtick strings to interpolate any valid JavaScript expression.
Question 5: What is a tagged template literal?
- A template literal with a type annotation
- A function called with the template's string parts and interpolated values as arguments (Correct answer)
- A template literal stored in a variable
- A template literal that escapes HTML automatically
Correct answer: A function called with the template's string parts and interpolated values as arguments
A tagged template literal prepends a function name to the template; the function receives the string parts array and the interpolated values as separate arguments.
Question 6: What is the ES2020 `??` (nullish coalescing) operator used for?
- Checking strict equality
- Returning the right-hand side only when the left-hand side is null or undefined (Correct answer)
- Short-circuit logical AND
- Coercing values to boolean
Correct answer: Returning the right-hand side only when the left-hand side is null or undefined
The `??` operator returns its right operand only when the left operand is `null` or `undefined`, unlike `||` which triggers on any falsy value.
Question 7: Which ES6 method returns a new array with all sub-array elements concatenated one level deep?
- Array.prototype.flat() (Correct answer)
- Array.prototype.concat()
- Array.prototype.reduce()
- Array.prototype.flatMap()
Correct answer: Array.prototype.flat()
`Array.prototype.flat()` flattens nested arrays by one level by default; pass a depth argument to flatten deeper.
What is the result of `[...'hello']`?