JavaScript ES6+ Features 2 — Questions and Answers
Question 1: What does the `Symbol.iterator` protocol enable in ES6?
- Making objects iterable with for...of loops (Correct answer)
- Creating unique property keys
- Defining getter/setter pairs
- Enabling prototype chaining
Correct answer: Making objects iterable with for...of loops
Implementing `Symbol.iterator` makes any object iterable, allowing it to be used with `for...of` and spread syntax.
Question 2: Which ES6 feature allows a function to pause execution and resume later?
- Promises
- Async/await
- Generator functions (Correct answer)
- Proxy objects
Correct answer: Generator functions
Generator functions, declared with `function*`, use the `yield` keyword to pause execution and resume on the next `.next()` call.
Question 3: What is the output of: `console.log(typeof Symbol('id'))`?
- 'object'
- 'string'
- 'symbol' (Correct answer)
- 'number'
Correct answer: 'symbol'
The `typeof` operator returns `'symbol'` for Symbol values, which is a primitive type introduced in ES6.
Question 4: What does `Array.from({length: 3}, (_, i) => i)` return?
- [undefined, undefined, undefined]
- [0, 1, 2] (Correct answer)
- [1, 2, 3]
- []
Correct answer: [0, 1, 2]
`Array.from` creates an array from an array-like object and applies the mapping function, using the index `i` to produce `[0, 1, 2]`.
Question 5: How do you define a private-like property using WeakMap in ES6?
- Store the instance as a key and the data as its value in the WeakMap (Correct answer)
- Use the `private` keyword inside the class
- Prefix the property name with `#`
- Use `Object.defineProperty` with enumerable: false
Correct answer: Store the instance as a key and the data as its value in the WeakMap
Before the `#` private field syntax, WeakMaps with the instance as the key were the idiomatic ES6 pattern for encapsulating private state.
Question 6: What is the difference between `Map` and a plain object for key-value storage in ES6?
- Maps only allow string keys; objects allow any type
- Maps allow any value as a key; objects coerce keys to strings (Correct answer)
- Maps are always faster than objects
- Objects support iteration; Maps do not
Correct answer: Maps allow any value as a key; objects coerce keys to strings
ES6 `Map` allows keys of any type (objects, functions, primitives), while plain object keys are always coerced to strings.
Question 7: What does the `...rest` parameter in `function f(a, b, ...rest)` collect?
- Only the third argument
- All arguments before `a` and `b`
- All arguments after `a` and `b` into an array (Correct answer)
- The prototype chain of arguments
Correct answer: All arguments after `a` and `b` into an array
The rest parameter `...rest` collects all remaining arguments after the named parameters into a real array.
What does the `Symbol.iterator` protocol enable in ES6?