The parameter of my function, when 1, assumes Boolean value and when False assumes Number value. How do I fix this? Javascript doubt

Asked

Viewed 59 times

-1

I’m right at the beginning of my studies with JS, so I got a little lost in this exercise.

I need to type check the single parameter of the 'check' function. When it is True, it returns False and vice versa, for booleans. When it is a Number returns its negation (e.g. 10, resume -10).

But when this parameter is false, it takes the value of a Number, in the case of 0 (and returns -0), when it is 1, it takes the value of a Boolean, in the case of True (and returns False).

I don’t understand why when the parameters are 0 or True, the function runs as expected.

function verifi(par){
    if (par == (true || false)){
        return !par
    } else if((par >= 0) || (par <= 0)){
        return par * (-1)
    } else{
        return "Não encontrado! O parâmetro é do tipo " + typeof par
    }
}

console.log(verifi(0)) //retorna -0, assim como esperado
console.log(verifi(1)) // deveria retornar -1, porém retorna false
console.log(verifi(false)) // deveria retornar true, porém retorna -0
console.log(verifi(true)) //retorna false, assim como esperado
  • 3

    Your first if seems to be the problem (true || false)

1 answer

2


When you do

if (par == (true || false))

you’re actually doing

if (par == true)

When making a comparison using == (equality comparison), some "unwanted" conversions are performed. For example, the following examples print true:

console.log(1 == true);
console.log([1] == true);
console.log("1" == true);

What you probably wanted to have done was used the comparison by identity (===) and use two separate comparisons:

if (par === true || par === false)

or

if (typeof par === "boolean")
  • 1

    Understood, I really made a mistake in these parts! Thank you very much for the help, it worked perfectly now.

Browser other questions tagged

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