Web Programming JavaScript Programming 2 — Questions and Answers
Question 1: What is a JavaScript Promise used for?
- Declaring constants
- Handling asynchronous operations (Correct answer)
- Creating class instances
- Defining modules
Correct answer: Handling asynchronous operations
A Promise represents the eventual completion or failure of an asynchronous operation and allows you to attach callbacks via .then() and .catch().
Question 2: Which array method creates a new array with elements that pass a test function?
- map()
- reduce()
- filter() (Correct answer)
- find()
Correct answer: filter()
The filter() method creates a new array containing only elements for which the provided callback function returns a truthy value.
Question 3: What does the arrow function syntax `const add = (a, b) => a + b` return?
- undefined
- A string 'a + b'
- The sum of a and b (Correct answer)
- A new function object
Correct answer: The sum of a and b
This arrow function with a concise body (no braces) implicitly returns the expression a + b, which is the sum of the two parameters.
Question 4: What is the purpose of the async/await keywords in JavaScript?
- To define synchronous timers
- To write asynchronous code in a synchronous style (Correct answer)
- To create web workers
- To import modules asynchronously
Correct answer: To write asynchronous code in a synchronous style
async/await is syntactic sugar over Promises that allows writing asynchronous code in a linear, synchronous-looking style, improving readability.
Question 5: Which JavaScript event listener method attaches an event handler to an element?
- onEvent()
- addEventListener() (Correct answer)
- attachEvent()
- bindEvent()
Correct answer: addEventListener()
addEventListener() attaches an event handler function to an element for a specified event type, supporting multiple handlers per event.
Question 6: What does the spread operator (...) do when used with an array?
- Deletes array elements
- Expands array elements into individual values (Correct answer)
- Sorts the array
- Reverses the array
Correct answer: Expands array elements into individual values
The spread operator expands an iterable like an array into its individual elements, useful for copying, merging arrays, or passing elements as function arguments.
What is a JavaScript Promise used for?