3

I am fairly certain this isn't a duplicate so please bear with me.

I check for boolean true||false using if() as a matter of course in my programming. I've programmed extensively in PHP, some in C# ASP.NET, a bit in Java, a long time ago in C++, & dabled in a few others. Checking for boolean true||false has always been pretty straightforward (as far as I could tell). But in JavaScript I've heard, read, and otherwise been told it's bad. That instead of:

if(var){}else{}

I should instead do:

if(typeof(var) !== 'undefined' || typeof(var) !== null || var !== ''){}else{}

I've always been a dabbler in JavaScript until the last 6 months when I've been getting steeped in it. After getting tired of writing & re-writing the long version of the boolean test shown above I finally asked a friend who's done extensive js development for years. My friend supported what I'd read, that I should never test for boolean true or false the way I'm used to. However, after that discussion I have a stronger belief that if(var){}else{} IS actually completely fine in js as it works EXACTLY like I would intuitively expect it to (my jsfiddle testing this)

I've looked around and found various links. The following seemed to be the more relevant:

The thing that convinced me most that my usage is safe and will work fine is the 3rd answer to the first SO question I linked to above given by Incognito. The js spec is very clear about what will & will not evaluate to boolean true||false, and again this is exactly as I would have expected (though have to be reminded that an empty array is an object... but that is specific to JavaScript, while the rest of it is exactly as I would expect).

Can someone please provide a definitive reason to not check for boolean true or false in JavaScrpt, realizing I know the difference between a boolean check and an equality check??

Thanks in advance!

Community
  • 1
  • 1
MER
  • 1,455
  • 20
  • 25
  • 1
    `typeof` isn't a function, but a language construction. Like `in`, `var`, `return`... – Ismael Miguel Jun 03 '15 at 00:59
  • 1
    if you do `if (foobar) {..}` and `foobar` doesn't exist, you will get a `variable is not defined` error – CrayonViolent Jun 03 '15 at 01:02
  • 1
    I think it's fine for most things, but often I do explicit checks. For example, if you're expecting a number and 0 is a valid option you've erroneously going to get a falsey result. – Jesse Kernaghan Jun 03 '15 at 01:03
  • @humble.rumble of course it is good practice to declare variables, and that would indeed solve the issue i pointed out, but that's not really the point of the OP I think? – CrayonViolent Jun 03 '15 at 01:05
  • @humble.rumble okay.. what is your point? MY point is that OP is asking why he can't just do `if (foobar) {..}` and I gave him a reason why. – CrayonViolent Jun 03 '15 at 01:09
  • umm..no? put this into a js console: `if (foobar) {console.log('true'); } else {console.log('false');}` if you do this and `foobar` is not defined, you get neither "true" nor "false". Instead, you get a js error. that is exactly my point. – CrayonViolent Jun 03 '15 at 01:17
  • for your own code, you shouldn't be; i totally agree that you should be at a minimum declaring your own vars. But for example, let's say you want to use some jQuery and you want to be safe and check if jQuery exists on your page first... how would you check that? if you simply did `if (jQuery) {..}` and jQuery is NOT on your page.. you get an error – CrayonViolent Jun 03 '15 at 01:20
  • I wouldn't call it a specialized case.. using 3rd party libs on a site is extremely common... – CrayonViolent Jun 03 '15 at 01:23
  • 1
    @CrayonViolent & humble.rumble I suspect we all basically agree. I would expect an error from the parser if I attempted to check the 'truthiness' of a variable that doesn't exist... – MER Jun 03 '15 at 02:37

4 Answers4

4

If a var is undefined, null or the empty string then it is falsey. You can rely on that as it is part of the specification of the language. It is totally acceptable and widely practiced to check if something is undefined by checking its truthiness.

bhspencer
  • 13,086
  • 5
  • 35
  • 44
  • but won't some script engines fail if you try to check an undefined variable? – IMTheNachoMan Jun 03 '15 at 01:29
  • 1
    …or if it is zero or false. – Bergi Jun 03 '15 at 01:29
  • 2
    @IMTheNachoMan: There's a difference between a variable that is not defined, and a variable that holds the value `undefined`. Confusing at first, but consistent amongst all script engines. – Bergi Jun 03 '15 at 01:30
  • @Bergi: I guess that makes sense. I just see a variable that holds undefined as undefined because from a memory perspective no memory is allocated for it. So if a function takes a parameter but you don't pass it then no memory is allocated for the variable. If I recall correctly... – IMTheNachoMan Jun 03 '15 at 01:42
  • @IMTheNachoMan: You seem to recall that incorrectly. The declaration of the variable alone (including parameter declarations) does allocate memory. And `undefined` is just a value as every other value and does take space in memory. – Bergi Jun 03 '15 at 01:45
3

Checking for boolean true||false has always been pretty straightforward. But in JavaScript I've heard, read, and otherwise been told it's bad.

No. Checking for a boolean value is just as straightforward in JavaScript as in every other language.

If var is a boolean (i.e. either true or false), then checking with if (var) {…} else {…} is fine and totally safe. No extra stuff to consider.

The problems that all the articles you linked refer to are with vars that are not boolean. JavaScript coerces them to booleans, and rules for that need to be memorized (the infamous "falsey" values). Be assured that those are much easier than the rules for using == on values of different types (that's what the first of your links is about, see also Which equals operator (== vs ===) should be used in JavaScript comparisons?).

But there's an easy way to stay out of trouble. You know what possible values the variables in your program can take (at least, those they are supposed to take). Make sure that you only pass booleans (including results of boolean expressions such as comparisons) to conditional statements, and make sure to never compare values of different types with each other).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Are you saying that you shouldn't check the truthiness of a variable? – bhspencer Jun 03 '15 at 01:45
  • @bhspencer: if you know that your variable is either `true` or `false`, then there's no need for that. If your variable is not a boolean, and you are not familiar with the concept of truthiness, always make your tests explicit (like `if (str != "")` instead of `if (str)` for non-empty strings). It saves you a lot of hazzle, especially if you're just learning the language. – Bergi Jun 03 '15 at 01:48
  • @humble.rumble: Yes, exactly. It's an important concept when learning JS, because there are some pitfalls where the pits are deeper than you'd expect (and there are no warning signs). Of course, there are still some things that you shouldn't use even if you understood them, like breaking from a labelled block (don't ask). – Bergi Jun 03 '15 at 01:55
  • @Bergi To restate, what I think you are saying is: Only use boolean checks on values that I have explicitly set as boolean values. So: var booleanVariable = false; However what I am talking about is relying on the js spec with an understanding of how that spec will interpret a given value in a boolean way such as: var aStringVariable = ''; (which will be seen as false because it's length is zero) OR var aStringVariable = "0"; (which will be seen as true because it's length is more than 1) So are you saying this second way (that is the way I want to be using it) is bad in some way? – MER Jun 03 '15 at 02:30
  • @Bergi just re-read your answer (again)... I think you are saying that it's fine so long as I know the rules for conversion to boolean? – MER Jun 03 '15 at 02:41
  • 1
    @MER: Yes exaclty. I say that you need to understand it (which, admittedly, is rather easy for the truthiness of strings). However, explicit is better than implicit, it will ease maintainance; especially for people who are not that fluent in JS. – Bergi Jun 03 '15 at 02:43
  • @Bergi that's a good & valuable point, other people having to maintain my code... dangit lol, might be a good enough point that I might have to continue to use the long check that I have grown a strong disliking for :) – MER Jun 03 '15 at 02:47
  • @MER if it is something you are using a lot, you might consider wrapping it in a function e.g. `isTrue(var)` that has the "long check". That way you can just do `if(isTrue(var)){..}` – CrayonViolent Jun 03 '15 at 03:49
  • @CrayonViolent: Except `isTrue` doesn't make sense in a condition. `isEmptyString` or `isNonEmpty` might be helpful however (even if too verbose imo). – Bergi Jun 03 '15 at 03:55
0

What about:

if (!!variable) {
    //Some code
}

Edit:

My mistake, don't use this. This exactly return the same as

if (variable) {
    //Some code
}
truongnguyen1912
  • 1,195
  • 8
  • 7
  • @humble.rumble it coerces it to a boolean, which some orgs use a stylistic indicator it's a truthy, such as the MooTools codebase – Andy Ray Jun 03 '15 at 01:07
  • !! means "Coerces var to boolean". http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – bhspencer Jun 03 '15 at 01:08
  • I see, thank you @humble.rumble. It should be used to cast a variable to boolean instead of for conditional check. – truongnguyen1912 Jun 03 '15 at 01:15
  • @humble.rumble: It will return the same in *all cases* actually. – Bergi Jun 03 '15 at 01:31
0

so first:

function test(someVar)
{
    return typeof(someVar);
}

test();      // return: "undefined"
test(null);  // return: "object"
test(false); // return: "false"
test(0);     // return: "number"
test("hi");  // return: "string"
test({});    // return: "object"
  • "undefined" is neither true nor false; it is undefined
  • how can something be true or false if it isn't there?
  • false, null, 0, and "" all equate to false
  • everything else is true

the idea of typeof(var) is to check if the variable was defined. A variable can be defined with the value of null, var blah = null, in which case the variable is defined but null.

using typeof(var) all depends on your code and what you're doing. sometimes i check and sometimes i don't.

IMTheNachoMan
  • 5,343
  • 5
  • 40
  • 89
  • 1
    your first example is loaded though.. since `someVar` is the defined first arg in the function definition, the function implicitly declares (but doesn't define) it. Try an equivalent in global scope! – CrayonViolent Jun 03 '15 at 01:18
  • @CrayonViolent: in the function definition it's a placeholder i think. nothing is there if nothing is passed in. no? – IMTheNachoMan Jun 03 '15 at 01:25
  • 2
    okay let me be more clear: your whole function is loaded. you are using `typeof` which is designed to operate against even undefined variables. Change your function to this: `function test(someVar){if (someVar){return "true";}else{return "false";}}` and you should get "false" if you run `test()`. Now change your function to e.g. this: `function test(someOtherVar){if (someVar){return "true";}else{return "false";}}` and run `test()` you will will instead get a js error – CrayonViolent Jun 03 '15 at 01:30
  • 1
    @humble.rumble I understand that. But the point I was making is that when the variable namespace is in the function arg, the function implicitly declares it. That's why I gave two functions to run using the `if(var){..}` condition instead. In the first, you can see that it the `else` executes, whereas in the 2nd one, it doesn't, and you get a js error instead. Why the difference? Because even though `someVar` is not defined in the first, it's implicitly declared by the function definition. – CrayonViolent Jun 03 '15 at 01:37
  • @CrayonViolent: I completely forgot about that scenario. Thanks! – IMTheNachoMan Jun 03 '15 at 01:44
  • @humble.rumble yet again you are missing my point and tbh i don't wanna go through another 20 rounds to get my point across to you. I'm not trying to be rude, but.. whatever man.. peace – CrayonViolent Jun 03 '15 at 01:44