privacyisimportant
privacyisimportant

Reputation: 31

Isn't it redundant to use "!!" in an if statement since if statments already check for truthy?

From my understanding !! is the preferred way to ensure a value is of Boolean type. So there are many cases where !! would be appropriate to use. However, in an if statement wouldn't it be redundant to use !! on a value since if statements already check for truthy?

var user = 'username123'

if (!!user) {
  // arbitrary code
}

So, I know I used a string here but it really shouldn't matter what type the variable is because I was under the assumption that the whole point of using !! is to ensure a Boolean type. In other words, !!user is just another way of doing Boolean(user). After carefully reading through the MDN docs for If..else it seems pretty clear that if statments already do this. Why then is there a need for !! inside an if statement? Or am I wrong and does !! actually convert values into a Boolean type more accurately or differently than the type coercion done by the if statment? Or is it one of those cases where I'm mostly right but there are exceptions where the conversions would result in different Boolean values?

Upvotes: 3

Views: 122

Answers (1)

Spectric
Spectric

Reputation: 32002

Yes, it is redundant. The if statement condition is always coerced to a boolean. The same applies for ternary operators.

Upvotes: 1

Related Questions