Information Technology IT – 21 Programming for the web | e-Consult
21 Programming for the web (1 questions)
Login to see all questions.
Click on a question to view the answer
Answer: Here's a JavaScript function that filters an array of numbers to return a new array containing only the even numbers, using a for...of loop:
Function:
function getEvenNumbers(numbers) {
const evenNumbers = [];
for (const number of numbers) {
if (number % 2 === 0) {
evenNumbers.push(number);
}
}
return evenNumbers;
}
Explanation:
- The function
getEvenNumbersaccepts an array of numbers callednumbersas input. - It initializes an empty array called
evenNumbersto store the even numbers. - The
for...ofloop iterates through eachnumberin thenumbersarray. - Inside the loop, the
ifstatement checks if the currentnumberis even by using the modulo operator%. Ifnumber % 2is equal to 0, it means the number is divisible by 2 and is therefore even. - If the number is even, it's added to the
evenNumbersarray using thepush()method. - Finally, the function returns the
evenNumbersarray, which contains only the even numbers from the input array.
Example Usage:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = getEvenNumbers(numbers);
console.log(evenNumbers); // Output: [2, 4, 6]