dimanche 18 mars 2018

Javascript Math.random() and conditional expressions

I would like to share with you my thoughts about this code:

for (var i = 1, max = 5; i < max; i++) {
    let random = Math.random();
    let expression = (random < 1 / (i + 1));
    if (expression){
        console.log('random is: ' + random + ' and the expression is: ' + expression + ', i is: ' +     i);
    }else{
        console.log('random was: ' + random + ' and the expression was: ' + expression + ', i was: ' + i);
    }
}

I was studying this example taken from GitHub: https://github.com/chuckha/ColorFlood

And I had trouble trying to know what was the meaning of the expression inside the if().

I used the JS repl: https://jscomplete.com/repl/

The context of this example is that this function would take a random index from 0 to 5, to map a random color to a Node.

Here we have a sample output from the repl:

"random was: 0.7118559117992413 and the expression was: false, i was: 1"
"random was: 0.478919411809795 and the expression was: false, i was: 2"
"random was: 0.4610390397998597 and the expression was: false, i was: 3"
"random was: 0.7051121468181564 and the expression was: false, i was: 4"




Aucun commentaire:

Enregistrer un commentaire