If statement with only a number in Javascript

8.1k views Asked by At

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?

4

There are 4 answers

2
Paul S. On BEST ANSWER

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
}
0
Leo On

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.

0
Tony On

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.

2
AJPerez On

If b is:

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

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