Tech Junkie Blog: JavaScript Array Methods : every() Method

Monday, June 4, 2018

JavaScript Array Methods : every() Method

The every() method is a method that tests a condition on every array element and makes sure that all the elements meets the criteria.  It returns true or false.

The code below test to see if the oil prices array is greater than $50 or greater than $70


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var greaterThanFifty = oilPrices.every(function (value) { return value > 50; });

        var greaterThanSeventy = oilPrices.every(function (value) { return value > 70 });

        console.log("greaterThanFifty: " + greaterThanFifty);
        console.log("greaterThanSeventy: " + greaterThanSeventy);
    </script>







As you can see the first condition is true because all of the elements in the array are greater than 50.  However, the second condition returns false because 69.50 is not greater than 70 even though the rest of the elements in the array are greater than 70.

No comments:

Post a Comment