By the end of this lesson, you will build a searchable product catalogue using JavaScript. This project is an excellent way to practice your coding skills and understand how this programming language functions. Also, it provides an opportunity for you to enhance your understanding of arrays and search functionalities.
A product finder or searchable catalogue helps users find specific items easily. For example, imagine a shoe store that allows customers to search for their favorite brand or style. This feature makes shopping more convenient and efficient. Furthermore, searchable product lists can enhance the overall user experience on websites.
In this section, we will go through the steps to create your own product catalogue. First, define your products in an array. Next, you will implement the search functionality.
File: catalogue.js
const products = [
{ name: 'Nike Air Max', price: 120 },
{ name: 'Adidas Superstar', price: 90 },
{ name: 'Puma RS-X', price: 110 }
];
function searchProducts(query) {
return products.filter(product => product.name.toLowerCase().includes(query.toLowerCase()));
}
console.log(searchProducts('nike')); // Output: [{ name: 'Nike Air Max', price: 120 }]
[{ name: 'Nike Air Max', price: 120 }]
This code defines a list of products with their names and prices. The searchProducts function takes a search query as input. It filters the product list and returns items that match the search term. The toLowerCase() method ensures that the search is case-insensitive. As a result, this feature is critical for a good user experience.
Now, create your own product catalogue. Add at least five products to the products array. Implement the search functionality as shown. Additionally, use console.log to test your results! For more information on getting started with JavaScript, check out this lesson. This lesson outlines how to connect a JavaScript file and run your first program.
const products = [
{ name: 'Reebok Classic', price: 75 },
{ name: 'New Balance 574', price: 85 },
{ name: 'Under Armour HOVR', price: 100 },
{ name: 'Converse All Star', price: 65 },
{ name: 'Vans Old Skool', price: 70 }
];
function searchProducts(query) {
return products.filter(product => product.name.toLowerCase().includes(query.toLowerCase()));
}
console.log(searchProducts('vans')); // Output: [{ name: 'Vans Old Skool', price: 70 }]
toLowerCase(): This can make searches case-sensitive. Always apply this method for a better search experience.includes() correctly in the filter function. Therefore, pay attention to syntax and logic in your code.filter() method to create a search function.