6

I am refactoring a bunch of old code and see that JSCS shows a warning about implicit type conversion for !!someVar statements.

Is it correct to replace all these implicit conversions with Boolean(someVar) so that nothing breaks due to this change?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • 1
    Doing the same in disguise doesn't strike as a good practice. Disabling that warning would be cleaner IMO. But your question isn't about opinion, I guess, and it's not clear to me. Are you asking whether the documentation you link to is faulty ? – Denys Séguret Jul 26 '16 at 15:01
  • 3
    No. The global `Boolean` variable might be overwritten/shadowed, the `!!` cannot. – Bergi Jul 26 '16 at 15:03
  • Some linters look like they try too hard to justify their existence. Those "implicit type conversions" are standard, efficient and explicit enough practices. – Denys Séguret Jul 26 '16 at 15:04
  • @Bergi Can't pretty much any code be broken by overwriting and shadowing? – Katana314 Jul 26 '16 at 15:06
  • @Katana314 Operators in JS can't be shadowed, hopefully. The result of `!!someValue` is always a boolean. – Denys Séguret Jul 26 '16 at 15:06
  • @Katana314: Most, yes, but not all. – Bergi Jul 26 '16 at 15:06
  • 1
    While static analysis tools are *immensely* valuable, some of their rules tend to be paranoid. Turning those off (I prefer to do so at the project level) is not a bad idea. – ssube Jul 26 '16 at 15:07
  • @ssube: It's not paranoia that is the reason for this rule, but "explicit is better than implicit" taken to the extreme. Turning it off might still be a good idea as it's only useful for newbies that don't know JS idioms. – Bergi Jul 26 '16 at 15:13
  • @Bergi isn't "taken to the extreme" a good description of paranoia? The tool *should* have all of the rules that are *potentially* useful and allow you to pick the ones you want (that was the problem with jslint). – ssube Jul 26 '16 at 15:18
  • @ssube: I'd call that simply "extremism". The inverse rule, forcing the usage of operators and not trusting the globals (fearing they are compromised) would be "paranoid". But yes, either rule is not useful. – Bergi Jul 26 '16 at 15:22

2 Answers2

8

Is it 100% correct to replace !!someVar with Boolean(someVar)?

No. The global Boolean variable might be overwritten/shadowed, the !! operators cannot.

Is it correct to replace all these implicit conversions with Boolean(someVar) so that nothing breaks due to this change?

Yes. If your code breaks because of this change, it should be considered already broken, and you should fix the thing that messes with Boolean instead.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

As another option, you could disable that warning. Using truthiness/falsiness is pretty accepted in Javascript programming. Looks like you can just disable it for boolean and not the other types.

djechlin
  • 59,258
  • 35
  • 162
  • 290