2

In Javascript, is there any difference between if(!!isLoaded) and if(Boolean(isLoaded))?

I recently started working on an app where the previous developer did this a lot.

I ran a few tests and they both seem to convert strings "true" and "false" to the Boolean type, which I'm assuming is the main reason for doing this.

If they are indeed the same, what is everyone's opinion on which one is more readable?

4
  • Both will convert the strings "true" and "false" to the boolean value true. But yes, they do precisely the same thing. Commented Feb 14, 2017 at 0:45
  • 3
    more readable doesn't come into it - neither do what you want Commented Feb 14, 2017 at 0:46
  • 2
    There's little difference between them, and they're also equivalent to if(isLoaded) which I think is most readable. Commented Feb 14, 2017 at 0:53
  • Yes @Barmar is right (unsurprisingly) — those conversions are mostly used when you really want a real boolean value to keep track of; if it's just an if statement, there's no point because the evaluation of the if condition will do exactly the same thing anyway. Commented Feb 14, 2017 at 1:01

3 Answers 3

2

Both if (!!isLoaded) and if (Boolean(isLoaded)) will be equivalent to if (isLoaded), as JavaScript only looks for truthy values for if conditions. If you need the specific strings "true" and "false", you'll need to compare to that directly with if (isLoaded === "true").

Sign up to request clarification or add additional context in comments.

Comments

0

I personally feel the !! is easier to read. They both convert to boolean though.

However like jaromeda mentioned neither will work for this situation. Both string "true" and "false" result in true since values exist.

Comments

0

Empty String is already treated as negative condition in JS, Indeed,...

The following are treated as negative condition in JS :

  • 0 👉🏼 const v = 0 ; (!v) && doSomething()

  • Empty string 👉🏼 const v = '' ; (!v) && doSomething() ⬅ ⚠️ Attention please since your question is about casting String to Boolean.

  • false 👉🏼 const v = false ; (!v) && doSomething()

  • null 👉🏼 const v = null ; (!v) && doSomething()

  • undefined 👉🏼 const v = undefined ; (!v) && doSomething()

And those 5 values are equals using == and not equal using ===.


Otherwise , v is treated as positive condition.

let zero = 0 ;
let falseVar = false; 

console.log(` zero == falseVar ? `, zero == falseVar);
console.log(` zero === falseVar ? `, zero === falseVar);

let emptyString= ''
console.log(` zero == emptyString ? `, zero == emptyString);
console.log(` zero === emptyString ? `, zero === emptyString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.