If-statements: how does Javascript determine which string to print when there is only one limit in the if-clause

Fix the broken code (round 2)!

In this exercise there is a number of if-statements like these:
if (percentSharedDNA > 5) {
return ‘You are likely 1st cousins.’
if (percentSharedDNA > 2) {
return ‘You are likely 2nd cousins.’
if (percentSharedDNA > 0) {
return ‘You are likely 3rd cousins’

I’d expect it would need something like:
if (percentSharedDNA > 2 && percentSharedDNA < 6) {
return ‘You are likely 2nd cousins.’

But it doesn’t. Can someone explain how this works, please?

i would still use else if where possible. Although it has no effect on how the code works, makes it easier to read and understand

Given return means handing back data to the caller, signaling the function is done executing. So when percentSharedDNA = 7, percentSharedDNA > 5 is true, so a return keyword is reached

the other conditions are never reached, so you don’t have to check if value is less then 6


The way you have this written, you don’t need to add the condition percentSharedDNA < 6 because if you reach your second if, you already know that percentSharedDNA < 6.

The reason for this is because you already know that percentSharedDNA > 5 is false, otherwise you would not have reached the second if. If percentSharedDNA is not greater than 5, then this also means that it is less than 6. Therefore, there’s no need to test for a condition that you already know to be true.

@stetim94 If I understand your answer correctly in this case it only works if you put all the if-statements in descending order.

If you’d put percentSharedDNA > 5 after percentSharedDNA > 2 it wouldn’t yield the desired result because then it would return ‘You are likely 2nd cousins.’

you understand correctly :slight_smile:

1 Like