Skip to content Skip to sidebar Skip to footer

Javascript: If Statement With Boolean And String Comparison Giving Unexpected Results

In my code I have the following: console.log(props.acknowledged) // false console.log(props.type === 'SOMETHING') //false console.log(!props.acknowledged && !props.type ===

Solution 1:

You need to add parantheses like this: !(props.type === "SOMETHING")

The priority of ! is more than === operator so your code will be evaluated as below:

!(props.type) === "SOMETHING"

so if props.type equals say "something else", it will become binary value of false and your whole expression is something && false which is false.

I think what you wanted to to is:

!(props.type === "SOMETHING")

or even

props.type !== "SOMETHING"

Solution 2:

!props.type is negating the string, which is coercing the string to boolean (true in this case) which results in false. You are then comparing false to "SOMETHING" with strict equality which will always result in false. anything && false will always result in false

As others have stated, the solution is to move the not into the comparison:

props.type !== "SOMETHING"

Just wanted to help explain the quirks of javascript's typing


Solution 3:

The expression !props.type will convert props.type to boolean. If it's a string, then !props.type means (props.type != ""). The subsequent === comparison to the string "SOMETHING" will always be false.

To put it another way,

!props.type === "SOMETHING"

is definitely not the same as

props.type !== "SOMETHING"

Perhaps what you meant was

!(props.type === "SOMETHING")

The unary ! operator binds more tightly than ===.


Post a Comment for "Javascript: If Statement With Boolean And String Comparison Giving Unexpected Results"