Is there any reason to do boolean casting with !! instead of Boolean() in JavaScript?
Asked Answered
C

7

5

I am aware of Boolean(), String() and Number() casting, and the '' + ..., !!... and +... casting approaches.

I am wondering if there is any reason to not use the function constructors?

Cinquefoil answered 14/3, 2011 at 18:26 Comment(12)
!! and others are unintentional syntactic sugar. I prefer the constructor approach as it is more readable. If you run it through a compressor/minifier, it can convert it into the uglier yet more compact version.Kella
!! is perfectly readable in my opinion. I prefer those shortcuts.Ecospecies
No, both methods produce the same result.Barde
@Ecospecies Imagine you've just read 500 lines of code and you come to x=!!0; for example. Then look at this: x = new Boolean(0);. You really think !!0 is more readable?Kella
@Travis: That's a bad example to be honest. That one looks ugly because that are just four ugly tokens together. Also you just remove the spaces in the first one. I mean, e.g. !!someVariable is really compact and nice.Ecospecies
See this question.Alkalinity
@Travis Boolean(0), not new Boolean(0).Barde
@Ecospecies So you propose I should do var x = 0; !!x ? You're changing the semantics. Sorry, you're wrong. I bet you think Perl is a beautiful language.Kella
@Travis: One-letter variables are perhaps not a good example, but the one I stated is preferable for me. But that's just my opinion :) I guess you like XML with all the typing?Ecospecies
There's a difference between which is more compact and which better conveys the intentions of the programmer. I bet you could ask fresh CS grads if they know what the purpose of !! is and at least half wouldn't know. My point being: Boolean(x) more clearly conveys what is trying to be achieved than !!x.Peebles
To be fair Andrew, most fresh CS grads wouldn't know what a prototypical language is either.Prophylaxis
The !! and such are also available in other languages like PHP, btw.Cinquefoil
P
4

In general the use of !! is often discouraged, as it's not clear to those who haven't seen it before what the actual purpose of it is. That said, it is less than a third the characters of Boolean().

Further, I'm not sure how often you actually need to cast to a boolean in Javascript, as it is often implicitly cast since Javascript is weakly typed.

Peebles answered 14/3, 2011 at 18:32 Comment(6)
Well to be honest I'm not super-sure I want somebody to mess with my code anyway if they're not familiar enough with JavaScript to know what "!!" means. :-)Frigid
@pointy, I think there's probably plenty of good programmers who just haven't been exposed to !! and wouldn't know what it's trying to do without either stopping to think about it or looking it up. I don't think I've ever seen !! used in JS, most of the time it's in C/C++.Peebles
Personally, as a hobby programmer I've come it across quite a many times. I understand your point, though. I guess whether or not to use !! depends on the code guidelines one has got to obey to.Ecospecies
I'm not 100% serious about that, but I do think that even great programmers unfamiliar with JavaScript should really study it, because there are a lot of landmines - particularly for long-time Java or C# programmers who've grown to see the world that way ...Frigid
@primvdb: Definitely. @Frigid I agree, there's definitely quite a bit about Javascript that trips up a lot of those unfamiliar with the language (== vs ===, implicit ;, etc.), especially if they consider it "just a browser scripting language".Peebles
I agree with @Pointy. Further, it is possible for the Boolean constructor to be modified while the "!" operator is immutable. Use !!. It is terse and means the same thing across many languages. I agree that for a single-language developer this could give pause; however, that's how one learns. Teaching and coaching less experienced developers is the way to go.Exanthema
F
3

Using the new operator with those function constructors can have unreliable effects on the typeof operator. (Edit: As the comments correctly note, this is only when using new Boolean() instead of Boolean())

For example,

var f = new Boolean(true);
if(typeof(f)==="boolean") {//false, since its an object, not boolean
 ....
}

JavaScript Garden has some great examples.

Foxtrot answered 14/3, 2011 at 18:33 Comment(3)
Without the new keyword it works fine though. typeof Boolean(1) === "boolean".Ecospecies
The OP was referring to Boolean(), not new Boolean(). Those are two different things. Also, new is an operator, not a constructor.Barde
@Sime Vidas fixed, and added a clarification that it doesn't apply for cases where new isn't used. Thanks!Foxtrot
R
2

I can think of 7:

  1. B
  2. o
  3. o
  4. l
  5. e
  6. a
  7. n
Riplex answered 14/3, 2011 at 18:32 Comment(0)
A
2

This shouldn't be an issue, but someone could replace the Boolean function with their own making the two ways not equivalent. For example:

Boolean = function(x) {
    alert('Evil');
    return !x; // Oops
}

var x = 0;
console.log(!!x); // false
console.log(Boolean(x)); // true

That's mostly a theoretical difference, since you shouldn't be replacing built in constructors, but it is a difference.

There could also be a small performance difference because of the name lookup and function call overhead. I wouldn't worry about either of those though in most cases. Just use whichever version you prefer.

Ahem answered 14/3, 2011 at 23:10 Comment(0)
A
1

It might just be a case of using less characters, making for a more compact script.

Astronavigation answered 14/3, 2011 at 18:29 Comment(0)
M
0

I find using new with these types can lead to easy confusion or tricky bugs:

var x = new Boolean(true);
console.log( x ); // true
console.log( typeof x ); // "object"

var y = new Boolean('false');
console.log( y ); // true
console.log( typeof y ); // "object"

var z = false;
console.log( z ); // false
console.log( typeof z ); // "boolean"
Milissa answered 14/3, 2011 at 18:47 Comment(2)
Just using Boolean(...) is actually the question if I'm not wrong. That also returns correct typeof results.Ecospecies
typeof ( new Boolean(false) ) === "object", whereas typeof false === "boolean". I think the implicit version is therefore less opaque. I suppose it's a matter of preference.Milissa
V
0

The Boolean(...) syntax is probably the best option, especially if you’re working on a large application with multiple developers. Code should be as readable as possible for any developer who joins the project.

Just as you should avoid using acronyms in your communication to ensure clarity for a wider audience, your code should also be easily understandable for most developers without needing additional research.

This time, we’re discussing the !! syntax, but there are many strange syntaxes in JavaScript. Reading such code for the first time can be challenging if efforts aren’t made to ensure readability. Moreover, even for experienced developers, it’s easier to work with clear and readable code.

This debate makes sense at the scale of !!, but at the level of an entire codebase, there’s no debate for me, so !! should be avoided.

Vladamar answered 8/11 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.