DEV Community

loading...
Cover image for JavaScript Made Easy: Part 15

JavaScript Made Easy: Part 15

David Tetreau
I am an up-and-coming Web Developer, and I love writing blog posts! I am currently looking for junior roles. Follow me on Twitter @david_tetreau
Updated on ・4 min read

For Part 14, we learned all about string methods. In this post, we will continue learning about JavaScript methods, but we will switch gears and talk about some of the more well known array methods. Open up your repl and code along!

Array Methods

push()

This method adds elements to the end of an array. Here's an example:

let colors = ["red", "blue", "green", "purple", "pink"];
colors.push("yellow");
console.log(colors);//"yellow" was added
Enter fullscreen mode Exit fullscreen mode

This method adds the string "yellow" to the end of the array. When you log the colors array to the console, it will contain six elements.

pop()

This method removes elements from the end of the array. When you log the shapes array to the console, it will contain four elements instead of five.

let shapes = ["triangle", "square", "rectangle", "circle", "oval"];
shapes.pop();
console.log(shapes);//"oval" was removed
Enter fullscreen mode Exit fullscreen mode

shift()

This method removes an element from the front of an array. When you log the birds array to the console, it will contain four elements instead of five because we removed one from the front of the array.

let birds = ["eagle", "sparrow", "cardinal", "crow", "parrot"];
birds.shift();
console.log(birds);//removed "eagle"
Enter fullscreen mode Exit fullscreen mode

unshift()

This method adds an element to the front of an array. When you log the insects array to the console, it will contain six elements instead of five because we added an element to the front.

let insects = ["bees", "ants", "termites", "beetles", "butterflies"];
insects.unshift("roaches");
console.log(insects);
Enter fullscreen mode Exit fullscreen mode

.length()

This method returns the length of the array. For example:

let coffee = ["black", "latte", "cappuccino", "americano"];
console.log(coffee.length);//4
Enter fullscreen mode Exit fullscreen mode

reverse()

This method reverses the values in an array. For example:

let numbers = [1, 2, 3, 4 , 5];
numbers = numbers.reverse();
console.log(numbers);//[5 ,4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

sort()

This method sorts an array. The default sort for this method is alphabetical order. Here's an example of the default sort behavior without parameters:

let fruit = ["mango", "pineapple", "grape", "peach", "kiwi"];
fruit = fruit.sort();
console.log(fruit);//logs the array in alphabetical order
Enter fullscreen mode Exit fullscreen mode

Another example of a default sort is with an array of numbers. The default sort for numbers is as follows:

let numbers = [5, 4, 3, 1, 2];
numbers = numbers.sort();
console.log(numbers);//logs the array in ascending order
Enter fullscreen mode Exit fullscreen mode

The sort method can also use parameters which determine the way the array is sorted. This example is from the MDN:

let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);// [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

As you can see, the numbers were logged in ascending order. In order to return the numbers in descending order, you would have to put b - a in the body of the function.

toString()

This method takes an array and converts it into a string. Here's an example:

let numbers = [4, 2, 5, 1, 3];
numbers = numbers.toString();
console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

concat()

This method enables you to combine two arrays together. Here's an example:

let techJobs1 = ["Software Developer", "Data Scientist", "IT Manager", "Information Security Analyst"];
let techJobs2 = ["Computer Systems Analyst", "Computer Network Architect", "Database Administrator", "Web Developer"]
const techJobs3 = techJobs1.concat(techJobs2);
console.log(techJobs3);//all the jobs in one array
Enter fullscreen mode Exit fullscreen mode

splice()

Splice can add to an array at specific indexes or replace items in array at specific indexes. Here's an example of both:

let videoGames = ["Grand Theft Auto V", "Tetris",  "Wii Sports", "Battlegrounds"];
videoGames.splice(1, 0, "Super Mario Bros.");
console.log(videoGames);
Enter fullscreen mode Exit fullscreen mode

This method inserted a string element at index 1 and replaced 0 elements. To better understand how splice() replaces elements, here is another example:

let videoGames = ["Grand Theft Auto V", "Tetris",  "Wii Sports", "Battlegrounds"];
videoGames.splice(1, 1, "Super Mario Bros.");
console.log(videoGames);//replaced Tetris
Enter fullscreen mode Exit fullscreen mode

slice()

This method makes a copy of a portion of an array but does not change the original array. The method takes two arguments and includes the first argument (which is an index, but does not include the second argument (which is also an index). Here's an example:

let movies = ["Army of the Dead", "Into the Darkness", "Sound Of Violence"];
const sliced = movies.slice(0, 2);
console.log(movies);//logs the original array
console.log(sliced);//logs two elements
Enter fullscreen mode Exit fullscreen mode

includes()

This method returns a boolean if an array contains a specified element or elements. Example:

const programmingLanguages = ["Python", "JavaScript", "Java", "C#"];
console.log(programmingLanguages.includes("Python", "JavaScript"));//true
Enter fullscreen mode Exit fullscreen mode

reduce()

According to w3schools, reduce() does the following:

  1. The reduce() method reduces the array to a single value.
  2. The reduce() method executes a provided function for each value of the array (from left-to-right).
  3. The return value of the function is stored in an accumulator (result/total).
  4. reduce() does not execute the function for array elements without values.

The syntax for reduce is as follows:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Enter fullscreen mode Exit fullscreen mode

The first two parameters inside of the function are required. The others are optional. An example of reduce is as follows:

let numbers = [15, 10, 5];
numbers.reduce(subtract);

function subtract(total, num) {
  return total - num;//subtracts from left to right
}
Enter fullscreen mode Exit fullscreen mode

filter()

This method creates a new array with the elements which meet the criteria specified in the function passed into filter(). Here is an example:

const grasses = ['bahia', 'bermuda', 'buffalo', 'centipede', 'bluegrass', 'ryegrass'];
const result = grasses.filter(word => word.length <= 5);
console.log(result);//returns only words less than or equal to 5
Enter fullscreen mode Exit fullscreen mode

map()

The map() method creates a new array with by calling every element in the array with a function. This occurs in order, and the original array is not changed. Here's an example:

const oddNumbers = [1, 3, 5, 7, 9];
const oddProduct = oddNumbers.map(multiplyByThree);

function multiplyByThree(num) {
 return num * 3;//every element is multiplied by 3
}

console.log(oddProduct);
Enter fullscreen mode Exit fullscreen mode

forEach()

This method runs a function for each element in an array. Here's an example:

const companies = ["Apple", "Google", "Facebook", "Netflix", "Amazon", "Microsoft"];

companies.forEach(company => {
    console.log(company);
});//logs them all to the console
Enter fullscreen mode Exit fullscreen mode

I hope you have enjoyed this post! Please check out the entire "JavaScript Made Easy" series by David Tetreau. There will be a new post daily(ish).

Discussion (0)