12. JSX Conditionals: &&

Can someone explain to me the logic behind this code. Thanks!.

var React = require('react');
var ReactDOM = require('react-dom');

// judgmental will be true half the time.
var judgmental = Math.random() < 0.5;

var favoriteFoods = (
    <h1>My Favorite Foods</h1>
      <li>Sushi Burrito</li>
      <li>Rhubarb Pie</li>
      {!judgmental && <li>Nacho Cheez Straight Out The Jar</li>}
      <li>Broiled Grapefruit</li>



When we use Math.random(), it will generate some random number between 0 and 1.
Suppose when you run your program first time, it may generate 0.3, which is less than 0.5. So

var judgemental = true


!judgemental = false

While using && operator if one of the condition becomes false, then the whole condition results as false. So the list

<li>Nacho Cheez Straight Out The Jar</li>

does not get rendered along with other list items.
If you run your code again and again Math.random() will generate different numbers , if the number is > 0.5, value of var judgemental becomes false. If number is < 0.5, value of var judgemental becomes true.
Hope this helps.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.