discodane
discodane

Reputation: 2095

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 === "SOMETHING") //false

How is that a !false && !false results to a false?

Upvotes: 0

Views: 113

Answers (3)

ganjim
ganjim

Reputation: 1416

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"

Upvotes: 2

mistahenry
mistahenry

Reputation: 8724

!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

Upvotes: 2

Pointy
Pointy

Reputation: 413737

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 ===.

Upvotes: 1

Related Questions