JavaScript JavaScript 3 — Questions and Answers
Question 1: What is a closure in JavaScript?
- A method that closes a browser window
- A function that has access to its outer scope's variables even after the outer function has returned (Correct answer)
- A way to terminate a loop early
- An error-handling mechanism similar to try/catch
Correct answer: A function that has access to its outer scope's variables even after the outer function has returned
A closure is formed when an inner function retains access to variables from its enclosing scope even after that outer function has finished executing.
Question 2: What will `[1, 2, 3].indexOf(4)` return?
- 0
- undefined
- -1 (Correct answer)
- null
Correct answer: -1
`indexOf()` returns `-1` when the specified element is not found in the array.
Question 3: Which of the following is NOT a valid way to declare a variable in modern JavaScript?
- var x = 1
- let x = 1
- const x = 1
- def x = 1 (Correct answer)
Correct answer: def x = 1
`def` is not a JavaScript keyword; variables are declared with `var`, `let`, or `const`.
Question 4: What is the result of `typeof NaN` in JavaScript?
- 'NaN'
- 'undefined'
- 'number' (Correct answer)
- 'object'
Correct answer: 'number'
Despite standing for 'Not a Number', `NaN` is of type `'number'` in JavaScript.
Question 5: What does the spread operator (`...`) do when used with an array?
- Joins array elements into a string
- Removes the last element of the array
- Expands the array's elements into individual values (Correct answer)
- Creates a deep copy of the array including nested objects
Correct answer: Expands the array's elements into individual values
The spread operator expands an iterable (like an array) into individual elements in places where multiple arguments or elements are expected.
Question 6: Which Promise method runs all promises in parallel and resolves when ALL of them resolve?
- Promise.race()
- Promise.any()
- Promise.all() (Correct answer)
- Promise.allSettled()
Correct answer: Promise.all()
`Promise.all()` takes an iterable of promises and resolves when all succeed, or rejects immediately if any one fails.
Question 7: In JavaScript, what does `Object.freeze()` do?
- Prevents the object from being garbage collected
- Makes all object properties read-only and prevents adding or removing properties (Correct answer)
- Creates a deep immutable clone of the object
- Serializes the object to a frozen JSON string
Correct answer: Makes all object properties read-only and prevents adding or removing properties
`Object.freeze()` makes an object immutable at the top level — existing properties cannot be changed, added, or deleted (but nested objects remain mutable).
What is a closure in JavaScript?