Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Write a program using the join()
, includes()
, and indexOf()
array methods you learned about earlier.
Resources
Why repeat search.toLowerCase()
vs. assigning it to a variable and reusing it? For example:
const search = prompt('Search for a product.');
const searchText = search.toLowerCase();
inStock.includes(searchText);
inStock.indexOf(searchText);
If the user clicks the "Cancel" button in the prompt dialogue, the variable searchText
would point to null
. The JavaScript interpreter throws an error when you call toLowerCase()
on a returned null
value -- there's nothing to convert to lowercase:
const search = prompt('Search for a product.');
const searchText = search.toLowerCase();
// Uncaught TypeError: Cannot read property 'toLowerCase' of null
Following is another way you might convert the value assigned to search
to all lowercase. If search
points to a truthy value (not null
, for example), then convert it to lowercase:
const inStock = [ ... ];
let message;
let search = prompt('Search for a product.');
if ( search ) {
search = search.toLowerCase();
}
if ( !search ) {
message = `<strong>In stock:</strong> ${inStock.join(', ')}`;
} else if ( inStock.includes(search) ) {
message = `Yes, we have <strong>${search}</strong>. It's #${inStock.indexOf(search) + 1} on the list!`;
} else {
message = `Sorry, we do not have <strong>${search}</strong>.`;
}
That way, you don't have to repeat calling toLowerCase()
in the conditional.
A different approach with only indexof()
There's another way you might write the product search without having to use includes()
to check whether the inStock
array includes a specific value. Remember, indexOf()
returns the index of a given element inside an array, or -1
if it's not present.
First, pass the search
value to indexOf()
. In the else if
clause, check if the product index is not -1
. Then use the value of productIndex + 1
to display the product's number in the list:
const inStock = ['pizza', 'cookies', 'eggs', 'apples', 'milk', 'cheese', 'bread', 'lettuce', 'carrots', 'broccoli', 'potatoes', 'crackers', 'onions', 'tofu', 'limes', 'cucumbers'];
let search = prompt('Search for a product.');
let productIndex;
let message;
if ( search ) {
search = search.toLowerCase();
productIndex = inStock.indexOf(search);
}
if ( !search ) {
message = `<strong>In stock:</strong> ${inStock.join(', ')}`;
} else if ( productIndex !== -1 ) {
message = `Yes, we have <strong>${search}</strong>. It's #${productIndex + 1} on the list!`;
} else {
message = `Sorry, we do not have <strong>${search}</strong>.`;
}
You need to sign up for Treehouse in order to download course files.
Sign up