Wednesday, February 19, 2025

JavaScript, Give example where all three parameters are used in predicate function


Give example where all three parameters are used in predicate function in JS:
const numbers = [4, 9, 16, 25, 29];
      let first = numbers.findIndex(myFunction);
      console.log('Number above 18:',numbers[first])
      function myFunction(value, index, array) {
        return value > 18;
      }


Here's an example where all three parameters (value, index, and array) are used in the myFunction predicate function. Let’s modify myFunction to check if the value is above 18, is in an even index position, and is part of an array that has at least five elements.

const numbers = [4, 9, 16, 25, 29];

let first = numbers.findIndex(myFunction);
console.log('Number above 18:', numbers[first]);

function myFunction(value, index, array) {
  // Check if the value is above 18, is at an even index, and the array has at least 5 elements
  return value > 18 && index % 2 === 0 && array.length >= 5;
}
In this example:

value > 18 checks if the number is above 18.
index % 2 === 0 checks if the index is even.
array.length >= 5 checks if the array has at least 5 elements.
When you run this code, it will log the first number above 18 that is at an even index in an array with at least 5 elements.

No comments:

Post a Comment

Hot Topics