1

I found this function to put numbers in fractions and I am trying to figure out what everything means. There is one thing I can't figure out.

Here's the code:

function reduce(numerator,denominator) {
  var gcd = function gcd (a,b) {
    if (b) {
      return gcd(b, a%b);
    } else {
      return a;
    }
  };
  gcd = gcd(numerator,denominator);
  return [numerator/gcd, denominator/gcd];
}

What does the if (b) mean. I know that if there is just the variable in the if statement it is checking if the variable is true or false. How would this apply to a number? When would this go to the else statement?

Paolo Moretti
  • 47,973
  • 21
  • 95
  • 89
michaelpri
  • 3,301
  • 3
  • 29
  • 43

4 Answers4

9

This is to do with how things get converted to Boolean, i.e. whether something is truthy or not

if (0 || NaN || undefined) {                // these are "falsy"
    // this never happens
} else if (1 /* or any other number*/ ){    // these are "truthy"
    // this happens
}
Paul S.
  • 58,277
  • 8
  • 106
  • 120
3

If b is:

  • 0
  • null
  • undefined
  • NaN
  • Or an empty string ""

it will be evaluated as false. Otherwise, it will be evaluated as true.

AJPerez
  • 3,039
  • 8
  • 59
  • 82
0

Any expression in if statement will be implicitly converted to boolean before evaluated.

In the code you posted, it's usually used to check if a parameter is passed, in which case undefined is a falsy value and will be converted to false. AJPerez has given an answer on the falsy values (except for he forgot NaN).

function reduce(numerator,denominator){
    var gcd = function gcd(a,b){
    if (b) {
        // if two arguments are passed, do something
        return gcd(b, a%b);
    }  
    else {
        // only one argument passed, return it directly
        return a;
    }
  };
    gcd = gcd(numerator,denominator);
    return [numerator/gcd, denominator/gcd];
}

However, this approach may be buggy if the argument you're checking is indeed passed by falsy.

Leo
  • 11,955
  • 4
  • 37
  • 58
0

In javascript you can check if the variable is assigned by putting it in an if statement. If it has a value it will be true (well unless its value is false or 0). If it has no value or evaluates at null it will return false. Looks like they are verifying it has a value before passing it into the function.

Tony
  • 3,199
  • 1
  • 25
  • 46