Finding Things in an Array

Grade 7, page 6 of 14. A one-minute read.

Need to know if something's in your array? Use includes, just like with strings:

JavaScript
const guests = ["Olivia", "Lucas", "Sofia"];

console.log(guests.includes("Lucas"));
console.log(guests.includes("Buggsy"));

It prints

true
false

Perfect for a bouncer at a party. "Is your name on the list?"

Need to know where it is? Use indexOf, which gives the index of the first match, or -1 if it's not there:

JavaScript
const guests = ["Olivia", "Lucas", "Sofia"];

console.log(guests.indexOf("Sofia"));
console.log(guests.indexOf("Buggsy"));

It prints

2
-1

(Sorry, Buggsy. You're not on the list.)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning