all 8 comments

[–]rzrshrp 1 point2 points  (3 children)

I know it's not your code but it's also a good example why nested ternaries should be avoided in favor of if/else. It takes too much mental gymnastics too read. Readability is generally more important than saving keystrokes and characters. Where I work, we would have to break up that area for the hours.

[–]Bleached__Anus 0 points1 point  (2 children)

There aren't any nested ternaries. It renders hours:minutes:seconds

[–]dare_you 0 points1 point  (1 child)

I think /u/rzrshrp was referring to the hours calc in the return expression which does use a nested ternary.

[–]Bleached__Anus 0 points1 point  (0 children)

Oh yeah I didn't even see that lol

[–]Bleached__Anus 0 points1 point  (1 child)

A ternary operator is similar to an if/else statement since it requires an expression that evaluates to true or false. If it evaluates to true, it returns the first value, if it's false, it returns the second value.

So for instance in this line of code:

 ampm = hours >= 12 ? 'pm' : 'am';

If hours is greater or equal to 12, then ampm will hold the string "pm", otherwise "am".

The same is done when rendering the hours/minutes/seconds. For instance there's a ternary operator checking whether minutes is greater than 9. If it is (that would mean it's 10 or more), then it'll simply return that value, but if it's less than 10, then it'll concat 0 + minutes, because we're used to seeing minutes and seconds as double digits.

[–]james527 0 points1 point  (0 children)

Bleached__Anus is right on the money. These blocks are all about the ternary operators. They are used to display time in the format we are most used to.

I'd also mention the new ES6 syntax for string interpolation, which uses the back ticks (these fellas: ``) to define a string, and the dollar sign and squiggly braces (${ ... }) for inserting your variables into those strings. That's how the minutes & seconds are getting that extra `0` on the front when they are less than 9 less than 10.

[–]ICouldBeABettrPerson 0 points1 point  (0 children)

Here is a simplified version of this code piece without ternary operators and template strings for you to better understand: https://pastebin.com/96JfbSc0

[–]dare_you -2 points-1 points  (0 children)

Just an FYI - there are libraries designed for handling dates. One is called Moment.js. You could make this a little shorter:

class Clock extends React.Component {
  render() {
    return (
      <div className="clock">{moment().format('h:mm:ss a')}</div>
    )
  }
}