CIW JavaScript Specialist 3 — Questions and Answers
Question 1: What is a closure in JavaScript?
- A method that closes a browser window
- A function that retains access to its outer scope even after the outer function returns (Correct answer)
- A way to terminate an asynchronous operation
- An error thrown when a variable is out of scope
Correct answer: A function that retains access to its outer scope even after the outer function returns
A closure is a function that remembers variables from its enclosing scope even after that scope has finished executing.
Question 2: Which method is used to attach an event handler to an HTML element in modern JavaScript?
- attachEvent()
- on()
- addEventListener() (Correct answer)
- bindEvent()
Correct answer: addEventListener()
addEventListener() is the standard DOM method to register an event handler on a specified element for a given event type.
Question 3: What does JSON.stringify() do?
- Parses a JSON string into a JavaScript object
- Converts a JavaScript value into a JSON-formatted string (Correct answer)
- Validates whether a string is valid JSON
- Minifies a JSON object by removing whitespace
Correct answer: Converts a JavaScript value into a JSON-formatted string
JSON.stringify() serializes a JavaScript object or value into a JSON string representation.
Question 4: Which JavaScript keyword declares a block-scoped variable that cannot be reassigned?
- var
- let
- const (Correct answer)
- static
Correct answer: const
const declares a block-scoped variable whose binding cannot be reassigned after initialization.
Question 5: What is the purpose of the Promise.all() method?
- Runs promises sequentially and returns the first resolved value
- Returns a promise that resolves when all provided promises resolve, or rejects on first rejection (Correct answer)
- Cancels all pending promises in an array
- Converts callback functions into promises
Correct answer: Returns a promise that resolves when all provided promises resolve, or rejects on first rejection
Promise.all() takes an iterable of promises and returns a single promise that fulfills when all input promises fulfill, or rejects if any one rejects.
Question 6: In the context of the DOM, what does document.querySelector() return?
- All elements matching the CSS selector as a NodeList
- The first element that matches the specified CSS selector (Correct answer)
- A live HTMLCollection of matching elements
- An array of all matching element IDs
Correct answer: The first element that matches the specified CSS selector
document.querySelector() returns the first Element within the document that matches the specified CSS selector, or null if no match is found.
Question 7: Which JavaScript operator checks both value equality AND type equality?
- ==
- !=
- === (Correct answer)
- =
Correct answer: ===
The strict equality operator (===) returns true only when both the value and the data type of two operands are the same.
What is a closure in JavaScript?