-1

I'm messing with code that someone else wrote and I saw that he writes like this

if(i === true)

Is there a difference if I do it this way?

if(i)
A good person
  • 217
  • 1
  • 12
  • 5
    the former is a strict comparison and will check if `i` is an actual boolean true value. The latter will return true if `i` is any value that will evaluate true (truthy value), e.g. 1 will evaluate as true – CrayonViolent Sep 15 '22 at 19:58
  • 1
    thank you very much for your answer I think you should post this as an answer – A good person Sep 15 '22 at 19:59
  • I just want to know if this is the only difference – A good person Sep 15 '22 at 20:00
  • 3
    I would rather this be marked as a duplicate. Lots of existing questions asking the same thing :) – CrayonViolent Sep 15 '22 at 20:00
  • To add to @CrayonViolent, (i) is the same as (i == true) so the question really is == vs ===. And there are a bunch of questions related to that. – imvain2 Sep 15 '22 at 20:02
  • @Agoodperson "I just want to know if this is the only difference" - As far as your example is concerned, yes. – CrayonViolent Sep 15 '22 at 20:06
  • I didn't understand your question probably because of translation problems – A good person Sep 15 '22 at 20:07
  • 2
    See also: "[Is there ever a reason to write "if (myBoolean == true)" in a JavaScript conditional?](/q/13250176/90527)", "[Why aren't results of logical-not and strict comparison inverses of each other?](/q/13127126/90527)", "[Why is it good practice to use if (myBoolean === true) in JavaScript?](/q/13250664/90527)" – outis Sep 15 '22 at 20:20

2 Answers2

2

The first if statement is checking for exact equality, and will only run if i was exactly equal to true.

The second one is checking for whether i is truthy, which means the if statement would still run if i was something other than things such as null, undefined, or an empty string.

https://developer.mozilla.org/en-US/docs/Glossary/Truthy

user19513069
  • 317
  • 1
  • 9
jjroley
  • 157
  • 10
1

Using the comparison operator will return true if i is boolean true, but just having i will return true for any truthy value I.E: positive integers, non-empty strings, etc

Bruck
  • 33
  • 5