Tutorial: Array Functions - every()
Hey there, coder! Today we're going to explore another powerful array function in JavaScript: every()
. This function is used to check if all elements in an array satisfy a certain condition. Let's dive in!
The Problem: Check if any product in an inventory is out of stock
Imagine you're a store manager, and you need to check if any product in your inventory is out of stock. You have an array of objects, where each object represents a product with its name
, quantity
, and stock
status. Your task is to write a function that checks if any product is out of stock.
Create a sample inventory array
In your index.js
file, create a sample inventory array:
const inventory = [ { name: "Apple Watch", quantity: 10, stock: true }, { name: "Samsung TV", quantity: 5, stock: false }, { name: "Nike Shoes", quantity: 20, stock: true }, { name: "PlayStation", quantity: 0, stock: false },]
Write a function to check if any product is out of stock
Create a function isOutOfStock()
that takes the inventory
array as an argument. This function should return true
if any product is out of stock, and false
otherwise.
function isOutOfStock(inventory) { // Your code here}
Use the every() function
To solve this problem, we can use the every()
function, which returns true
if every element in the array satisfies the provided test function. In our case, we want to check if every product is in stock. If any product is out of stock, the function should return false
.
Add the following code to your isOutOfStock()
function:
function isOutOfStock(inventory) { return inventory.every((product) => product.stock)}
Here, we're using an arrow function as the test function for every()
. The arrow function takes a product
object as an argument and checks if its stock
property is true
. If any product has stock
set to false
, the every()
function will return false
.
Run the code and check the output
Click the "Run" button to execute your code. You should see the output in the console.
Expected Output:
false
This is because the Samsung TV
and PlayStation
products are out of stock.
Exercise: Modify the function to return an array of out-of-stock products
Modify the isOutOfStock()
function to return an array of products that are out of stock. Use the filter()
function to achieve this.
Hint: You can use the filter()
function to create a new array of products that have stock
set to false
.
When you're ready, click the "Run" button to see the output.
That's it! You've learned how to use the every()
function to check if every element in an array satisfies a condition. Well done!
Remember, practice makes perfect. Try experimenting with different array functions and scenarios to solidify your understanding. Happy coding!
Tests