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?

1

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

May be more concise to write x != 0 is truthy (either negative or positive)
@BradChristie NaN != 0; // true
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.

2 Comments

don't forget NaN :D
Added NaN. I thought of adding false too, but... :)
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.

Comments

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.

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.