0
const customer = [10, 10]; // input array

const lemonadeChange = function (bills) {  

let five = 0, ten = 0;

bills.forEach((ele, idx) => {

switch (ele) {
  case 5:
    five += 1;
    break;

  case 10:
    if (five === 0) {
      return false; //at this point the function should stop. Instead it proceeds. 
    }
    else {
      five -= 1;
      ten += 1;
    }

  case 20:
    if (five !== 0 && ten !== 0) {
      five -= 1, ten -= 1;
    }
    else if (five > 2) {
      five -= 3;
    }
    else {
      return false;
    }


}

})

return true; //the function should be returning false because the variable five has a value of 0;
}

Input: Integer array of size 2. Result: True Expected Result: False.

In the Switch case of 10, the function lemonadeChange should return false and stop execution. Instead, the function continues to loop through the array and the returns true outside the loop. I ran the code using a debugger and I still can't figure out why the return statement at case 10 isn't working. I would appreciate your help, thanks.

the_fro
  • 7
  • 1
  • 4
  • `(ele, idx) => { .. }` is an arrow function. And `return` _"stop"_ that function as expected. But it does not stop the `forEach` and does not exit the `function (bills) { ... }` function because the `return` does not belong to that function. – t.niese Nov 01 '18 at 19:16

1 Answers1

0

forEach() will execute the enclosed function for every element in bills. The return statement ends the function call, which just makes forEach() move on to the next element.

If you don't want to run through every element, you will need to use a for loop instead of forEach().

Cameron
  • 491
  • 2
  • 9