-2

This is my very first program in javascript! I've been trying to go through tutorials and I kind of get it. But my code doesn't work! I want to find out why??? An explanation of the error would help me understand.

document.write("Random # (1-5) = ", Math.floor((Math.random() * 5) + 1), "<br />");
if(Random = 2){
 alert("Your names Bob");
}else {
 alert("Your names Superman");
}

This program writes to the page a random number between 1 and 5, (works fine...) then, say, if the random number is 2, I want to alert the user that their name is Bob, and if the number isn't 2, alert them that their name is Superman...

Complete noob/beginner here, sorry if this frustrates you, but I appreciate your understanding! The only way to learn!!! Cheers :)

2
  • I had no idea grammer was an issue, i will try and be more clear with the way I write my questions on this website from now on, drinking and studying isn't the best solution. ;) Commented Apr 10, 2016 at 17:18
  • This question is similar to: If statements not working?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 12 at 17:53

1 Answer 1

3

your code is wrong, the first thing is that you should use "==" for comparison into if() (or "===" if you also want to check the type).

The second thing that I see is that you are checking the value of a variable called Random but the first line wrote some text on the page (document.write()) but it doesn't set the value of the Random variable, try replacing the first line with:

var Random = Math.floor((Math.random() * 5) + 1)

and this should work

Sign up to request clarification or add additional context in comments.

4 Comments

I only get the name bob though? i understand why the first code never worked now as a variable never existed and i was calling for a variable to be used, this is creating a random number but isnt finding the value of 2 and alerting me the correct name? thanks for the reply by the way!
var Random = Math.floor((Math.random() * 5) + 1) if(Random = 2){ alert("Your names Bob"); }else { alert("Your names Superman"); } This is the code i wrote (sorry im not sure how to code snippet in a comment?
This is because you are generating a lot of numbers but you enter the if() only if Random is exactly 2. If you want to show "bob" with every number divisible by two you have to change the if() to if(Random % 2 == 0).
Understand and got it! the code is working! thank you and really appreciate your time! ill carry on my tutorials on javascript, i just want to have a understanding of how javascript works so i can implement it into my website! awesome explanation btw! thanks again!