JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – Math random in if condition

JavaScript Quiz – Math random in if condition

Math random in if

In javascript, if-else is a conditional statement that changes the flow of code based on the condition pass to it. And on the other hand Math.random() gives a random floating value whose range is by default range from 0 to less than 1.

Basic Syntax of If else Condition

if (condition) {
  //  block of code to be executed if the condition is true
}

For more detail about the if else condition click here.

Basic Syntax of Math.random() function

Math.random()

For more detail about the random function click here.

JavaScript Question

In this javascript quiz, find out what happens if Math.random() function pass to if condition but random gives random value.

First, we declare a if-else condition and inside the if condition a Math.random() function is passed.

if(Math.random()){
 console.log(true);
} else {
 console.log(false);
}

And inside the if-else condition console log is passed one contain the true and other contain the false.

But Math.random() function value changed every time it is called. So, any idea what should be the output of the above statement.

JavaScript Quiz Test

Here is the full code snippet for you to solve.

if(Math.random()){
 console.log(true);
} else {
 console.log(false);
}

// output = ?

Answer – true

Click To Run Code

Explanation

Now, you know the answer is “true“. But why, because random function value is unsure. Let me explain.

We know that the random() function gives floating value but whose range is from 0 to less than 1.

Most of the time random give value more than 0 but it’s rare to get 0.

At last, That’s why we get an answer “true.

Let me know in the comment section, what you think about it.

I hope you understand the concept and logic behind it.

But wait, i have something more for you –

Check out our other javascript quiz – 

  1. JS Quiz – does the splice method replace array element
  2. JS Quiz – is the console log function really override
  3. JavaScript Quiz – delete work on object create method object
  4. JavaScript Quiz – null and undefined act as value in function parameter

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top
0 Shares
Share via
Copy link