JS Intro: (Math.random()*50); VS (Math.random())*50;

Hi, I’ve found it strange that the console gives me different solutions:

console.log(Math.random()*50); = 48.94737736434246

console.log(Math.random())*50; = 0.06602151311996107

Why is that? It seems that the system doesn’t care about the *50 if it isn’t in brackets. I would understand if it would give out an error but why does it outright ignore the *50 when not put inside the brackets?

Thanks for your help.

a = Math.random()
console.log(a * 50)
console.log(a) * 50

That last example is key. The return value of console.log() is undefined. Times that by 50 and JS returns, NaN. Notice that it still logged a.


Hi mtf, thank you for your reply.

Is there any logic behind why it doesn’t comply to commands outside the brackets when I log something?

1 Like

The parens are the demarcation of the arguments list. Anything outside of that will not be seen by console.log(), only the line interpreter, which parses that once the return value has come back from the method.

const addAB = (a, b) => a + b;

c = addAB(3, 4) * 6  // the return value times 6
console.log(c)    //  42

console.log(addAB(3, 4)) * 6

Any expression we write inside the parens will be evaluated before it is logged (as in before it is sent down to the method). The method itself has no return value, save undefined, which is not a number so any math done with it will result in the same, NaN.

edited 3 + 4 is 7, not 42

1 Like

Because the difference is essentially this:

Give me a number between 0 and 1 and multiply it by 50, and console log it

Give me a number between 0 and 1. Console log it. Then multiply by 50.

Once you’ve console logged it, it’s already a log and it’s printed.

1 Like

THANKS!!! You’re a genius!