Javascript Array Methods: includes(), indexof(), join()
Javascript has a set of built-in methods for manipulating arrays. In this article, we explore three of them:
includes()
checks if an array contains an itemindexof()
returns the index of an item in an arrayjoin()
converts an array into a string
Let’s take a detailed look into each of them.
includes()
The includes()
method checks an array to see if it contains an item. If it does, it returns true
to the caller else it returns false
.
Syntax
array.includes(item, searchFrom)
Parameters
It takes 2 parameters, the item to find and the position in the array to begin searching from. The second parameter is optional so it doesn’t have to be used.
Return value
Returns either true if the item is found or false if the item is not found.
Examples
const arr = [“a”, “b”, “c”];
arr.includes(“a”); // returns true
arr.includes(“x”); // returns false
arr.includes(“a”, 1); // returns false
arr.includes(“A”); // returns false
Note: includes()
is case-sensitive which is why the last statement returns false.
indexof()
The indexof()
method is quite similar to includes()
with the same syntax and parameters. The only difference is the return value which is the position in the array where the item is found.
Syntax
array.indexof(item, searchFrom)
Parameters
It takes two parameters: the item to search for and an optional parameter that’s the position in the array to search from.
Return value
The first index of the element in the array. If the item is not found, it returns -1.
Examples
const animals = [“dog”, “cat”, “rat”, “goat”, “chicken”, “dog”];
animals.indexof(“dog”); // returns 0
animals.indexof(“goat); // returns 3
animals.indexof(“cow”); // returns -1
animals.indexod(“dog”, 1); // returns 5
join()
The join()
method concatenates the element of an array and returns a string of the array items.
Syntax
array.join(separator)
Parameters
It has one optional parameter which is a string that separates each element of the array. Without specifying this parameter, the separator is a comma (,).
Return value
A string containing all the elements of the array
Example
const alphabets = [“a”, “b”, “c”];
alphabets.join(); // returns “a, b, c”
alphabets.join(“”); // returns “abc”
alphabest.join(“-”); // return “a-b-c”