Here is a tutorial on Array Functions - every() for JavaScript, with an example of verifying if all items in a shopping cart are available for shipping:
Tutorial: Array Functions - every()
Hey there, coder! In this tutorial, we're going to explore the every()
array function in JavaScript. We'll use it to verify if all items in a shopping cart are available for shipping.
Step 1: Create a shopping cart array
Open your index.js
file and create an array to represent a shopping cart. Add the following code:
const cart = [ { id: 1, name: "Shirt", available: true }, { id: 2, name: "Pants", available: true }, { id: 3, name: "Shoes", available: false }, { id: 4, name: "Hat", available: true },]
This array represents a shopping cart with four items, each with an id
, name
, and available
property indicating whether the item is available for shipping.
Step 2: Define a function to check availability
Create a function called isAvailable
that takes an item object as an argument and returns a boolean indicating whether the item is available for shipping. Add the following code:
function isAvailable(item) { return item.available}
This function is simple: it just returns the available
property of the item object.
Step 3: Use every() to check if all items are available
Now, let's use the every()
array function to check if all items in the shopping cart are available for shipping. Add the following code:
const allAvailable = cart.every(isAvailable)console.log(`All items are available: ${allAvailable}`)
The every()
function takes a callback function (in this case, isAvailable
) and applies it to each element of the array. If all elements return true
, every()
returns true
. If any element returns false
, every()
returns false
.
Step 4: Run the code
Click the "Run" button to execute the code. You should see the following output in the console:
All items are available: false
This is because the third item in the cart (Shoes) is not available for shipping.
What's happening behind the scenes
When we call cart.every(isAvailable)
, the every()
function iterates over the cart
array and applies the isAvailable
function to each element. If any element returns false
, the iteration stops, and every()
returns false
. In this case, the third item returns false
, so every()
returns false
.
Conclusion
In this tutorial, we learned how to use the every()
array function to check if all items in a shopping cart are available for shipping. We defined a function isAvailable
to check the availability of each item and used every()
to apply this function to each element of the array.
Next, we'll explore the map()
array function, which is used to transform an array by applying a function to each element. Stay tuned!
What's next?
Click the "Next" button to proceed to the next tutorial, where we'll learn about the map()
array function.
Tests