Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use if (!!err)?

In this code sample from the sequlize docs:

if (!!err) {
    console.log('Unable to connect to the database:', err)
} else {
    console.log('Connection has been established successfully.')
}

Why are they using (!!err) to test that err's truthiness? Isn't that the same as if (err)?

like image 876
eric Avatar asked Dec 05 '22 23:12

eric


1 Answers

Why are they using (!!err) to test that err's truthiness?

There's no reason. Maybe they're overcautious, having heard some wrong things about thruthiness? Or they want to emphasize the ToBoolean cast that occurs in the evaluation of the if condition?

Isn't that the same as if (err)?

Yes.

if (err)
if (Boolean(err))
if (!! err)

all mean exactly the same thing. The latter two only doing unnecessary steps in between before arriving at the same result.

like image 168
Bergi Avatar answered Dec 08 '22 12:12

Bergi