Includes
Lesson 8 of 18 in Coddy's Array Methods in JavaScript course.
The includes() method is a built-in function on JavaScript arrays that determines whether a specific element exists within the array. It returns true if the element is found and false otherwise. This method provides a concise and efficient way to check for element presence without manual looping.
includes()performs a case-sensitive search by default. For example,"apple"won't match"Apple".
// Shopping cart items
const cartItems = ["Milk", "Bread", "Eggs"];
// Check if "Apples" are already in the cart (not added yet)
const hasApples = cartItems.includes("Apples");
console.log(hasApples); // Output: false (Apples not found)
// Customer adds "Apples"
cartItems.push("Apples");
// Now check if "Apples" are in the cart
const hasApplesNow = cartItems.includes("Apples");
console.log(hasApplesNow); // Output: true (Apples added successfully)
This example demonstrates how includes() helps ensure each item is added only once to the shopping cart, enhancing the user experience.
Challenge
EasyJacks scores are stored in the given array named jackScores.
Write JavaScript code to check if Jack achieved a perfect score (100) on any of his quizzes and log the result at the end.
Try it yourself
const jackScores = [85, 92, 78, 100, 89];
// Write code here