The problem is in the following expression:
valor1 > valor2 || valor1 < valor2
She will always evaluate a true
, since the operators >
or <
do not return the largest number, but rather a boolean, depending on the comparison of greater than or less than, respectively.
Therefore, you must remain the condition and return the number if it is true:
function igual(valor1, valor2) {
if (valor1 === valor2) {
return 'Iguais.'
} else {
if (valor1 > valor2) {
return valor1;
} else {
return valor2;
}
}
}
console.log(igual(5, 5));
console.log(igual(5, 6));
You can also use a single expression using a ternary operator to decide which is the smallest number:
function igual(valor1, valor2) {
if (valor1 === valor2) {
return 'Iguais.'
} else {
return valor1 > valor2 ? valor1 : valor2;
}
}
console.log(igual(5, 5));
console.log(igual(5, 6));
But as mentioned in another answer, Making a function return two different types is not a very advisable practice. Maybe you should group them into a kind of data structure:
function igual(valor1, valor2) {
if (valor1 === valor2) {
return { equal: true, biggest: valor1 };
} else {
return {
equal: false,
biggest: valor1 > valor2 ? valor1 : valor2
};
}
}
console.log(igual(5, 5));
console.log(igual(5, 6));