Edit: This is not a duplicate! This is specifically asking about the combination of an if statement with the Ternary Operator. The other threads do not address this, nor is it asked there as far as I can tell. The confusing part for me was that the Ternary Operator replaces one of two if statements where one if statement is inside another one.
My question also contains sub questions (which may or may not be ideal) that also weren't being addressed in the other threads.
Here's the original question: Can someone help me understand how this code works, please?
I found it on this site. Here: Calculate the LCM of two or three numbers in JavaScript
function gcd2(a, b) {
// Greatest common divisor of 2 integers
if(!b) return b===0 ? a : NaN;
return gcd2(b, a%b);
}
Firstly, I thought the ternary operator was supposed to be used instead of an if function. Here they're used together?
The way I read the code is as follows:
if b is undefined, the if statement returns "false" (because b===0 is false when b is undefined), but it also assigns "a" to something, but to what? And why? Does "return b===0" end the function? And then it assigns NaN to something when b is not undefined. Why?
I hope to understand the rest of the code once I understand the first part.