Search code examples
javascriptsyntax-errorfeedback

JavaScript Syntax Error or More?


I am an extremely new (read as three hours old) amateur with JavaScript so I have an extremely low level question. However I thought it would offer a great chance to explore this stackoverflow community. I have run through approx 50% of the CodeAcademy JavaScript intro and just finished the section on while and for loops. On the free practice section I decided to try and write a program to simulate a coin flip 1,000 times and report the results to the user. The program seems to run OK but on line 9 I am seeing a hint that syntax is wrong as I introduce an if/else statement. Also I now see that if you answer "no" it runs anyways. What is wrong with the syntax and what other general feedback do you have on my very first independent program? Thanks!

var userReady = prompt("Are you ready for me to flip a coin one thousand times?");

var flipCount = 0;

var heads = 0;

var tails = 0;

if (userReady = "yes" || "Yes") {
    flipCount++;
    while (flipCount <= 1000) {
        var coinFace = Math.floor(Math.random() * 2);
        if (coinFace === 0) {
            heads++;
            flipCount++;
        } else {
            tails++;
            flipCount++;
        }

    }

} else {
    confirm("Ok we'll try again in a second.");
    var userReady = prompt("Are you ready now?");
}


confirm("num of heads" + " " + heads);
confirm("num of tails" + " " + tails);

var userReady = prompt("Are you ready for me to flip a coin one thousand times?");

var flipCount = 0;

var heads = 0;

var tails = 0;

if (userReady = "yes" || "Yes") {
  flipCount++;
  while (flipCount <= 1000) {
    var coinFace = Math.floor(Math.random() * 2);
    if (coinFace === 0) {
      heads++;
      flipCount++;
    } else {
      tails++;
      flipCount++;
    }

  }

} else {
  confirm("Ok we'll try again in a second.");
  var userReady = prompt("Are you ready now?");
}


confirm("num of heads" + " " + heads);
confirm("num of tails" + " " + tails);


Solution

  • This line:

    if (userReady = "yes" || "Yes") {
    

    does not do what you expect it to. First, you cannot use = to compare values (it means assignment in Javascript). So you can use ===. Second, the || joins two independent conditions, not values. So you can write:

    if (userReady === "yes" || userReady === "Yes") {
    

    Additionally, you can cover the case where the user types something like YES or yEs by normalising the case of the user input before comparison:

    if (userReady.toLowerCase() === "yes") {