JavaScript ES6+ Features 4 — Questions and Answers
Question 1: What happens when you use `new` with an arrow function?
- It creates a new object normally
- It throws a TypeError because arrow functions cannot be constructors (Correct answer)
- It returns `undefined`
- It uses the parent scope's `this`
Correct answer: It throws a TypeError because arrow functions cannot be constructors
Arrow functions lack a `[[Construct]]` internal method, so calling `new` on them throws a `TypeError`.
Question 2: What does `Object.assign({}, obj1, obj2)` do?
- Deep-clones both objects
- Merges own enumerable properties of obj1 and obj2 into a new object shallowly (Correct answer)
- Creates a prototype chain from obj1 and obj2
- Freezes the resulting object
Correct answer: Merges own enumerable properties of obj1 and obj2 into a new object shallowly
`Object.assign` copies own enumerable properties from source objects into the target, performing a shallow merge.
Question 3: In ES6 destructuring, what does `const { a: renamed } = obj` accomplish?
- Creates a new property 'renamed' on obj
- Extracts obj.a into a variable named 'renamed' (Correct answer)
- Renames obj.a to 'renamed' in obj
- Throws a SyntaxError
Correct answer: Extracts obj.a into a variable named 'renamed'
The `: renamed` syntax in destructuring assigns the value of `obj.a` to a local variable called `renamed`.
Question 4: What is the purpose of `Proxy` in ES6?
- To create a copy of an object
- To intercept and redefine fundamental operations on an object (Correct answer)
- To freeze an object's properties
- To serialize an object to JSON
Correct answer: To intercept and redefine fundamental operations on an object
A `Proxy` wraps an object and intercepts operations like property access, assignment, and function calls via handler traps.
Question 5: Which of the following is a valid use of computed property names in ES6?
- const obj = { [key]: value } (Correct answer)
- const obj = { (key): value }
- const obj = { #key: value }
- const obj = { ${key}: value }
Correct answer: const obj = { [key]: value }
ES6 computed property names use square brackets `[expression]` inside an object literal to use a dynamic expression as the property key.
Question 6: What does `Set` guarantee about its stored values?
- Values are stored in insertion order and each value appears only once (Correct answer)
- Values are sorted numerically
- Values must be primitive types
- Duplicate values are stored with a count
Correct answer: Values are stored in insertion order and each value appears only once
ES6 `Set` stores unique values in insertion order; adding a duplicate has no effect.
Question 7: What is the output of: `const [a, , b] = [1, 2, 3]; console.log(a, b);`?
- 1 2
- 1 3 (Correct answer)
- 2 3
- undefined 3
Correct answer: 1 3
Array destructuring with a hole (,,) skips the element at that position, so `a` gets 1 and `b` gets 3.
What happens when you use `new` with an arrow function?