How to use 'Else if' correctly?

Asked

Viewed 119 times

3

I built a function called min which returns the smallest number that is passed in one of its two arguments. When the numbers are equal it returns null. I was able to make the code work as follows:

function min(a,b){
    if(a != b){
        if(a<b){
            return a; 
        }else{
            return b; 
        }
    }else{
        return null;
    }
}

Initially I made the code as follows:

function min(a, b){
    if(a<b){
        return a; 
    }else if(a = b){
        console.log('They are the same')
    }else{
        return b;
    }
}

Only that it didn’t work, it returns correctly only the first if(a<b), if the arguments do not fall in this first case, the function returns continuously null.

What mistake of logic am I making in this second case?

  • 1

    Comparison between values is performed with == and not with =.

2 answers

5


The = is the allocation operator, then a = b is actually setting the value of the variable a, which becomes the same value as b. Then this value is tested according to those rules (and as any non-zero number is considered "true", any values of b that are different from zero will cause you to enter this if - if you have not entered the if previous, of course).

For example:

let a;
let b = 10;

if (a = b) { // a recebe o valor de b
    console.log(a); // 10
}

a = b causes a receive the value of b, that is 10.

So deep down we’re testing if (10), and as non-zero numbers are considered true, he enters the if and prints the value of a (in the case, 10).

So to fix, you can use == (the equality operator) or === (strict equality operator). The difference is that the first can convert types between values (for example, '10' == 10 is considered "true"), while the second does not make this conversion and checks if the values are also of the same type (ex: '10' === 10 is "false", but 10 === 10 and 1 + 9 === 10 are "true"). Read here for more details.


That being said, if the idea is to return the lowest value (or null if both are equal), nor would need to test equality, could do so:

function min(a, b) {
    if (a < b) return a;
    if (a > b) return b;
    return null;
}

console.log(min(1, 2)); // 1
console.log(min(10, 2)); // 2
console.log(min(2, 2)); // null

The return returns the given value and quit the job (that is, if you arrived at a return, it does not execute the rest of the function code). Therefore it does not need the else.

If you enter the first if it is because a is smaller, then returns it and does not need to perform the rest. If not entered in this if, it is because a is greater than or equal to b.

If you enter the second if it is because b is smaller, so returns it and does not need to perform the rest.

If you don’t get into any of the if's, it is because a and b are equal, so I can return null without even needing another if there (after all, if it did not enter any if it is because a is not smaller or greater than b, So the only alternative that’s left is that they’re the same, and so you don’t even have to test that again, it’s redundant and unnecessary).


Another detail is that I don’t like the idea of a function that, depending on the case, returns something or prints something and returns nothing (which is what you tried to do in the second code).

I prefer that the function always returns something, and whoever called it does whatever you want with the returned value (including printing a message, if applicable):

function min(a, b) {
    if (a < b) return a;
    if (a > b) return b;
    return null;
}

let result = min(2, 2);
if (result === null) {
    console.log('Não tem menor, os números são iguais');
} else {
    console.log(`O menor número é ${result}`);
}

This way you separate the responsibilities well: the function only returns the result (the smallest of the numbers, or null if they are equal), and whoever called the function takes some action as the result - may even print the message, and although it seems that it gives in the same, does not give, because so you do not depend on the message that is within the function and can take the action you want in each case (for example, if I do not want to print any message, or do anything else, etc).


And for the record, when a function can’t find one return, she ends up returning undefined. That is, in this function:

function min(a, b){
    if (a < b){
        return a; 
    } else if (a = b) {
        console.log('They are the same');
    } else {
        return b;
    }
}
console.log(min(2, 1)); // undefined

Like a is greater than b, he doesn’t enter the first if. There in the else if happens what has already been explained: a receives the value of b, and since this is not zero, it is evaluated as "true". So get into this if, prints the message "They are the same" and as no return is executed, the function returns undefined (and not null, as you said, because they are not the same thing).

0

Peter missed only == on his if E.

Instead of comparing with == you were assigning with the =.

Follow code below with correction.

function min(a, b){
    if(a<b){
        return a; 
    }else if(a == b){
        console.log('They are the same')
    }else{
        return b;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.