0

I want to write a function that returns true if there exists at least one number that is larger than or equal to n.

Below is my code. I am trying to use array methods and ternary operators.

function existsHigher(arr, n) {
  let newArr = [];

  arr.forEach(e => {
    if (n>e) {
      newArr.push(n)
    }
  })
  console.log(newArr)
  (newArr.length !== 0) ? true:false
}

existsHigher([5, 3, 15, 22, 4], 10) //➞ should return true

My code is returning:

enter image description here

What am I doing wrong?

PineNuts0
  • 4,740
  • 21
  • 67
  • 112
  • 3
    **Always** use semicolons unless you're *sure* you understand the rules for ASI, but even then, it's probably not a good idea. Also, you need to `return` on that last line for the expression to be returned (and the conditional operator is unnecessary, you can just use `return newArr.length > 0`) – CertainPerformance Jul 29 '19 at 01:51
  • 1
    All fine ideas, but I'm not sure any of them are what's actually wrong with the code. – Robert Harvey Jul 29 '19 at 02:02
  • yes, the ternary doesn't work even with the added semicolons – PineNuts0 Jul 29 '19 at 02:15
  • As @CertainPerformance said, you have to `return` the ternary. Just change the last line in that function to `return newArr.length > 0` (because you don't even need the ternary) – Modermo Jul 29 '19 at 02:49
  • @RobertHarvey The error OP is seeing is definitely due to the lack of a semicolon just before the last line in the function, and for the desired output, OP just needs to add the `return` to the last line for the expression that follows it to be returned, otherwise the function will return `undefined` by default (and the last line there, which comes up with the output he wants, will just be an unused expression) – CertainPerformance Jul 29 '19 at 02:51

0 Answers0