Start learning free

LESSON 115 OF 675 · ARRAYS I

Checking an Array for a Value in TypeScript

Lesson

TL ; DR:

arr.includes(x) is true when the array holds x, and false when it doesn't. Use it as the condition of an if.


let colors = ["red", "green", "blue"];

console.log(colors.includes("red"));    // true

console.log(colors.includes("pink"));   // false

if (!colors.includes("pink")) {
    console.log("No pink yet");
}


Full lesson:

Often you need to know if an array holds some value. Is this name on the guest list? Is this item in the cart?

includes(x) answers that. It compares each item with x, from the first one on. It returns true as soon as one matches, or false if none does.

Put ! in front for the opposite. So !colors.includes(x) is true when x is missing.

The answer is a boolean, so it fits right into an if:

let cart = ["milk", "bread"];

if (cart.includes("milk")) {
    console.log("Milk is in the cart");
}

The name is includes, not contains. Arrays have no contains method.

Text must match exactly. So colors.includes("Red") is false, because the array has "red".


Your task

bag holds what is packed for a hike.

If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.

Expected output:

Water is packed
Pack a tent
STEP 1 OF 2
    Ctrl + Enter to check