Can sb explain this code pls?

function findElement(arr, func) {
  return arr.length && !func(arr[0]) 
    ? findElement(arr.slice(1), func)
    : arr[0];
findElement([1, 2, 3, 4], num => num % 2 === 0);

what are you having issues understanding? what do you already understand of this code?

I don’t understand the point of using arr.length. I got the point of using the ternary operator.

if the array is empty, so arr.length is 0, arr[0] doesn’t exist, so it just avoid that

Thanks. What is the point of the exclamation mark?

Used like that, it evaluates if the expression its attached to is truthy or falsy and returns the opposite value. For example !5, would return false, because the value of 5 is truthy. Trying !0 is true, because 0 is falsy value. As you can see, even if the value you test is not boolean, the operator will convert it to boolean, so there are two main uses, to flip the value of a boolan and to convert a non boolean value to boolean(to use in a condition for example). You could also say !!5, which would return the boolea value of 5, which is truthy(the first ! sign converts to boolean and flips the value and the second sign flips it once more, so as result we get the original boolean value).

I often find it helpful when trying to understand the posted solutions to compare it with the code you wrote. Key elements of the logic will often line up with the logic that you figured out.

Thank you for your help:)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.