1. 24
    var weAreConnected = Math.floor(Math.random() * 10) > 5;
    
    if (weAreConnected === true) {
      this.setState({
        isConnected: true
      })
    } 
    else {
      this.setState({
        isConnected: false
      })
    }
    

    What? It’s difficult to take the article seriously after that. Seems like a purposely obfuscated example for saying:

    var connected = Math.random() > 0.5;
    this.setState({isConnected: connected});
    

    And it’s not about not being fluent with JS either. This is just basic boolean stuff.

    1. 6

      The connected variable isn’t reused anywhere either so couldn’t you just do this?

      this.setState({isConnected: Math.random() > 0.5});
      

      I’d use a ternary statement for setting the color too, but I know some people don’t like those.

      1. 4

        The connected variable isn’t reused anywhere either so couldn’t you just do this?

        Yep, absolutely, in this simple case, i wouldn’t mind either way. But splitting the calculation into its own variable, even though the variable is not reused anywhere else, has some benefits:

        1. Each line is does a one simpler thing: first determine whether we’re connected using a random value, and then set the component state to that.

        2. The code is more debugger-friendly. You can easily tell the value of the connected variable before setting the state by stepping between the two lines.

        I’d use a ternary statement for setting the color too, but I know some people don’t like those.

        Well, ifs in JavaScript are not expressions, so i’d use ?: too :)

        1. 1

          I’d use a ternary statement for setting the color too, but I know some people don’t like those.

          Do you know why ternary statements would be frowned upon? I don’t like nested ternaries, but other than that I find them extremely useful and they aren’t really that hard to use…

          1. 3

            It’s because they’re often used with poor taste. I use them for one-line assignments all the time, but they’re sometimes used nested or with conditions/values complex enough that they span multiple lines.

            1. 1

              The new do expression in the early parts of the standardization process will make this process much nicer if it makes it.

            2. 2

              I had a CS professor from Bulgaria in college that would always chastise me for using them in C telling me “You’re being clever; be clear, not clever.”

              1. 2

                To me, any C code is clever, not clear.

          2. 6

            You’re just too much of a hacker. Not everybody can write this kind of code.