0
function and(arr) {
  if (arr.length === 0) {
    return true;
  }

  const head = arr[0];
  const tail = arr.slice(1);

  return head && and(tail);
}

and([true, true, false]);

I have this recursion called 4 times and at the end

if (arr.length === 0) {
    return true;
  }

I thought it would end with

However, the function has only been called 3 times !!

head: [true]    tail: [true,false]
head: [true]    tail: [false]
head: [false]   tail: []

This is the result I checked

  if (arr.length === 0) {
    return true;
  }

This condition didn't even work.

I need help.

Sorry for using the translator

3
  • change return head && and(tail); to return and(tail);. Commented Nov 22, 2020 at 12:09
  • @cybercoder Then the function would be guaranteed to return true, which goes against the whole point of the function. Commented Nov 22, 2020 at 12:14
  • @Aplet123 the question is about count of calling happens in recursion! So he/she have to change the body of function to achieve correct answer. I made a comment to guide not an answer! Commented Nov 22, 2020 at 13:49

1 Answer 1

5

In Javascript and many other languages, && is short-circuiting. This means that if you have a && f(), and a is false, the condition is already known to be false, so f is never ran. Since the head of your array is false in the third call, the && operator will short-circuit and return false without even continuing the recursion. If you try and([true, true, true]) you will notice that it does go all the way to a 0-length array and your condition will do something.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.