0

x = 4;
console.log(x);
var x = 10,
  y = 2;

function z(x) {
  while (x > 0) {
    if (x > 0) {
      break;
    } else {
      x = x - y;
      return z(x);
    }
    return x;
  }
}
console.log(x);
console.log(z(x) + z(x + y));

I need explain for the output of the last line?, where the output is NaN.

Barmar
  • 741,623
  • 53
  • 500
  • 612

6 Answers6

1

Because z(x) and z(x + y) are returning undefined.

1

It is returning NaN because when you call...

console.log(z(x)+z(x+y));

not all paths within the function return anything. In fact, in the if block it just breaks and nothing is ever returned.

        if(x>0){
           break;
        }

If x == 10 then the while loop will just break and nothing is returned. You can fix this by switching out the break; for return x; which is ultimately doing the same thing but not returning NaN.

        if(x>0){
           return x;
        }
Matthew
  • 184
  • 6
0
function z(x) {
  while (x > 0) {
    if (x > 0) {
      break;
    } else {
      x = x - y;
      return z(x);
    }
    return x;
  }
}

For this function, think about the case of x === 10. The while condition is true, so we enter that. Next. We get to the if (x > 0), which is true, so the break; statement is hit. This breaks out of the while loop, and we exit the function with no return value. Thus, z(x) returns undefined.

z(x + y) similarly returns undefined if you follow the same logic.

undefined + undefined === NaN

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • The `while` condition is `x > 0`, so that if/else statement is pointless. The while loop already checks the condition on each iteration. Perhaps you should explain what you want the function to do so we can weigh in on what should be modified. – Jacob Aug 12 '20 at 15:42
  • Modify condition if(x > 0) to if (x <= 2) – The Hopeful Aug 12 '20 at 15:45
0

whatever you want to be done, you function does not return anything by itself. Just add return:

function z(x) {
  display.log(x, y)
  while (x > 0) {
    if (x > 0) {
      break;
    } else {
      x = x - y;
      return z(x);
    }
    return x;
  }
  return x /// this is what was added
}
Tarukami
  • 1,160
  • 5
  • 8
0

It happens because hits break when x > 0:

 if (x > 0) {
  break; 
FBlade
  • 361
  • 1
  • 8
0

function z() is always returning undefined. So :

z(x) & z(x+y) are undefined

Javascript addition on undefined values returns NaN. So

z(x) + z(x+y) is NaN
ankur1812
  • 97
  • 4