Master working with arrays and their powerful built-in methods in JavaScript.
Example demonstrating common array methods:
// Define an array of numbers
const numbers = [1, 2, 3, 4, 5];
// Use map() to create a new array with each number doubled
const doubled = numbers.map(num => num * 2);
// Use filter() to get numbers greater than 2
const filtered = numbers.filter(num => num > 2);
// Use reduce() to sum all numbers
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
// Output results
console.log('Original:', numbers);
console.log('Doubled:', doubled);
console.log('Filtered (>2):', filtered);
console.log('Sum:', sum);
This code demonstrates:
map() for transformation.filter().reduce().Arrays: Ordered collections of values stored under a single variable. Arrays can hold any type of data including numbers, strings, objects, and even other arrays.
Common Array Methods:
push() - Adds one or more elements to the end.pop() - Removes the last element.shift() - Removes the first element.unshift() - Adds elements to the beginning.map() - Creates a new array by applying a function to each element.filter() - Creates a new array with elements that pass a test.reduce() - Executes a reducer function on each element to reduce the array to a single value.forEach() - Executes a function for each element (no return).find() - Returns the first element that satisfies a condition.includes() - Checks if an array contains a value.sort() - Sorts the array elements.These methods empower developers to manipulate arrays efficiently and elegantly in JavaScript.
Q1: Which method creates a new array by applying a function to every element?
filter()map()reduce()forEach()Answer: B. map()
Q2: How do you remove the last element from an array?
pop()shift()unshift()splice()Answer: A. pop()
Q3: What does the reduce() method do?
Answer: C. Combines all elements into a single value.
Q4: Which method checks if an array contains a specific element?
find()includes()indexOf()some()Answer: B. includes()