Reveal the Boolean value

Asked

Viewed 34 times

1

I have a function that checks whether the numbers passed nor arguments are equal if they are not wanted to show the highest number. But I don’t know how to show the greatest....

function igual(valor1, valor2) {
  if (valor1 === valor2) {
    console.log('São valores iguais')
  } else {
    let maior = valor1 > valor2 || valor1 < valor2
    return `O maior numero é: ${maior}`
  }
}
console.log(igual(5, 6)); // dá "true"...

2 answers

3

To know the biggest number you can use the Math.max (also described in this other question), But in general I do not advise to have a function that returns either Boolean or number... it is better to have the same typing. But you can return two values to the Python style.

A suggestion would be so:

function igualEMaior(...valores) {
  const iguais = valores.every((val, i, arr) => arr[0] === val);
  return [iguais, Math.max(...valores)];
}

const [igualA, maiorA] = igualEMaior(4, 5, 6);
console.log(igualA, maiorA); // false 6

const [igualB, maiorB] = igualEMaior(4, 4, 4);
console.log(igualB, maiorB); // true 4

1


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));

Browser other questions tagged

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