JavaScript Glossary - Lesson #9

JavaScript Array .includes() Method

This method checks if an array contains a given element. The return value for this method is a Boolean. true if the element exists in the array and false if otherwise.

js
[10, 20, 30, 40].includes(50)
// False
js
//  Create an array of names
const classNames = ['amazon', 'facebook', 'google', 'scotch']

// Verify inclusion in classNames
let partOfClass = classNames.includes('microsoft')

console.log(partOfClass)
// output: false

Array.includes():

  • Takes a value as an argument
  • Checks the array if the value exists within the array
  • Returns true or false.
  • If no argument is provided, it returns false.
js
array.includes(searchValue, startIndex)

searchValue This is the value to search the array for.

startIndex (optional) This the position in the array at which the search begins.

The method will return an the Boolean true if the array contains the searchValue and false if it doesn’t. If no arguments are provided, false is returned by the method.

js
const names = ['Johnny', 'Pete', 'Sammy']
const myName = 'Pete';

const hasMyName = names.includes(myName);
console.log(hasMyName);
// output: true

The includes method is commonly used to check if an array has a certain value in it.

Search Days of the Week

js
// Weekdays
const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

// Random month
const month = 'May';

// Verify inclusion in array
const isDay = days.includes(month);

console.log(isDay);
// output: false

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)