How to usefor loop approach in Javascript

In this approach we are iterating through the array elements using the for loop in JavaScript and using the custom every function we will apply the condition function on the array elements, if the condition is satisfied then the custom every function will return true else it will return false.

Example: In this example, we will see the use of the for-loop approach.

Javascript




function customEveryFunction(arrayElements, conditionFunction) {
    for (let i = 0; i < arrayElements.length; i++) {
        if (!conditionFunction(arrayElements[i])) {
            return false;
        }
    }
    return true;
}
let numbersInput = [2, 4, 6, 8, 10];
let allEvenResult = 
    customEveryFunction(
        numbersInput, num => num % 2 === 0);
console.log(allEvenResult);
  
let geekInput = 
    ["w3wiki", "forgeeks", "geek"];
let allStartingWithAResult = 
    customEveryFunction(
        geekInput, word => word.startsWith("g"));
console.log(allStartingWithAResult);


Output

true
false


Implement a Function that Accept Array and Condition and Returns Boolean Values in JavaScript

In JavaScript language every function is a special function that checks the element of the array with the condition given in the input, Each element is checked against the condition, and if the condition is satisfied then every function returns the true result else if any of the element of the array fails against the condition then the false result is been returned. In this article, we will see three different approaches through which we can implement the custom every function which will accept the array and the condition function and also it will return the true result if all the elements of an array satisfy the condition.

Table of Content

  • Using for loop approach
  • Using the Array.prototype.filter method

We will explore all the above approaches along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using for loop approach

...

Approach 2: Using the Array.prototype.filter method

In this approach we are iterating through the array elements using the for loop in JavaScript and using the custom every function we will apply the condition function on the array elements, if the condition is satisfied then the custom every function will return true else it will return false....

Contact Us