Welcome to our deep dive into ES6 Array Methods! In this lesson, we'll explore various methods that make working with JavaScript arrays more efficient and practical. 📝
Array methods are functions that operate directly on arrays, allowing us to manipulate, filter, and sort data effortlessly. These methods were introduced in ES6 (a version of JavaScript) and are essential for any JavaScript developer.
push() 📝Adds one or more elements to the end of an array and returns the new length of the array.
let fruits = ['apple', 'banana'];
fruits.push('orange', 'grape'); // fruits now contains ['apple', 'banana', 'orange', 'grape']pop() 📝Removes the last element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange', 'grape'];
let lastFruit = fruits.pop(); // lastFruit contains 'grape', fruits now contains ['apple', 'banana', 'orange']shift() 📝Removes the first element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange', 'grape'];
let firstFruit = fruits.shift(); // firstFruit contains 'apple', fruits now contains ['banana', 'orange', 'grape']unshift() 📝Adds one or more elements to the beginning of an array and returns the new length of the array.
let fruits = ['banana', 'orange', 'grape'];
fruits.unshift('apple'); // fruits now contains ['apple', 'banana', 'orange', 'grape']What does the `push()` method do?
map() 📝Creates a new array with the results of calling a provided function on every element in the array.
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num); // squares contains [1, 4, 9, 16, 25]filter() 📝Creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0); // evenNumbers contains [2, 4]reduce() 📝Reduces an array to a single value by iterating through each element, applying a provided function to the current and previous values.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((acc, num) => acc + num, 0); // sum contains 15What does the `filter()` method do?
With ES6 array methods, manipulating arrays in JavaScript becomes a breeze! We've learned the basic and advanced methods, but there's much more to explore. Remember, practice makes perfect, so keep coding! ✅
Stay tuned for more lessons on CodeYourCraft! 🎯