ES6 Array Methods 🎯

beginner
14 min

ES6 Array Methods 🎯

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. 📝

What are Array Methods?

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.

Basic Array Methods

push() 📝

Adds one or more elements to the end of an array and returns the new length of the array.

javascript
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.

javascript
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.

javascript
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.

javascript
let fruits = ['banana', 'orange', 'grape']; fruits.unshift('apple'); // fruits now contains ['apple', 'banana', 'orange', 'grape']

Quiz Time 💡

Quick Quiz
Question 1 of 1

What does the `push()` method do?

Advanced Array Methods

map() 📝

Creates a new array with the results of calling a provided function on every element in the array.

javascript
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.

javascript
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.

javascript
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((acc, num) => acc + num, 0); // sum contains 15

Quiz Time 💡

Quick Quiz
Question 1 of 1

What does the `filter()` method do?

Wrapping Up

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! 🎯