Junior Developer Central JS Practice Exercise - 20

 
Question: 

Write a Javascript function that returns true if the provided predicate function returns true for all elements in a collection, false otherwise. 




Answer: 

function checkFunction(arr, fn) {
  for (let i = 0; i < arr.length; i++) {

    if (!fn(arr[i])) {
      return false;
    }

  }
  return true;
}




> we declare a function 'checkFunction' 
> it has two parameters 'arr' & 'fn' 
> we want to return false if 'fn' (which is a function) returns false for even one element in 'arr' (which is an array)
> our function should return true if the function 'fn' returns true for all elements in array 'arr'
> so in order to check the result of the function 'fn' on each and every element of array 'arr' we use the for loop
>  we additionally use the if statement to check the boolean value on each iteration of the for loop
> we return false if the condition is met and the loop is terminated
> we keep the iterations running till all the elements of the array are checked and terminate the loop by returning 'true'

Comments

Popular posts from this blog

Junior Developer Central JS Practice Exercise - 22

Junior Developer Central JS Practice Exercise - 21

Javascript Practice 68: JS Hero - do...while loop