12

Today I found out that
true + 1 is 2 in js

Comments
  • 4
    What I don't like about javascript is that it always try to please other and can't say no.

    Even if you try to make it do something which doesn't make sense, it always try to give the output somehow.

    I try to include the type information in variable name to prevent such problem.
  • 8
    Kinda makes sense if you take
    True / 1
    False / 0
  • 1
    @mr-user That was pretty much done back in the 90's because even though some dev would write a ballsed up onClick event, the page wouldn't throw an error and go tits up on the users. Other parts of the page would still be usable.
  • 2
    @Ranchu
    And also this -_-
    true + true = 2
    true + 'xyz' = 'truexyz'
  • 1
    @theuser ah.. I see.. they wanted to make js tolerable and ended up with quite opposite
  • 1
    @24th-Dragon Not sure what you're trying to do. First example is just 0 + 1. If you store "", then post increment, it will be 1.

    So
    let x = ""
    x+++true
  • 1
    @devGaara what the fuck
  • 3
    Newsflash, most languages store boolean values as 0 and 1 (actually all languages, since, you know, computers operate in binary)... Now, how much is 1 + 1? That's right, 2.
  • 3
    I'm not into javascript but I've already seen that true+true=2 thing once in code. I understand it but my strongly-typed mind hurts 😆
  • 0
    @theuser jokes on you, you are just doing
    (x++) + true.
    Which changes the variable to a number (since it was empty string -> 0)
    And then post increment operator bla bla.
    Executing same line again gives different results that way.
  • 1
    @vorticalbox True, although it is probably a better idea to box the values for the sake of clarity.

    Boolean("1") //true
  • 1
    And why would one add boolean to number, again? Aren't you supposed to multiply them? I mean, lol, it's pure logic, how long you can go with type inference if you make such confusing operations :)

    EDIT: Oh, it's an interview question? Well, then my complaint is addressed to interviewer, because they lack logic.
  • 0
    @vintprox I was asked in an interview
  • 3
    Here's a cute use case: you've got 3 boolean variables, and you need to know if at least 2 of them are true.

    You can just write (var1 + var2 + var3) >= 2.
  • 0
    @hitko aye! That's a neat little trick. Thank you
  • 0
Add Comment