13
devGaara
43d

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

Comments
  • 5
    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
  • 3
    "" + + true
    Result: "1"
    "" ++ true
    Result: Syntax error
  • 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.
  • 4
    Why do people see type coercion and see it as a bad thing, it's extremely powerful once you get your head around it.

    Say you the front end it sending you "1" and "0", for true and false you can turn this into a bool with

    !!+"1" //true
    !! +"0" // false

    +"1" the plus turns this into the number 1

    !1 == false
    !false == true

    Magic.
  • 2
    @vorticalbox True, although it is probably a better idea to box the values for the sake of clarity.

    Boolean("1") //true
  • 0
    @theuser im just trying to show how easy it is to mess up with type coercion. the guy is surprised 1 + true is 2.
  • 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
Add Comment