Search code examples
javascriptarraysif-statementsyntax-errorvar

Javascript - Uncaught SyntaxError: Unexpected token 'else'


Its my first time learning to program Javascript and been working on this program to take 99 drinks on the wall till it reachs zero.. I been working on this program since 12am learning JS... its now 3am and im going bonkers and unable to see my mistake.

Where did i go wrong? How can i prevent this in the future?

Its my first crack at making a JS program so please dont rip into me too bad i litterly just opened a book and started at 11:30pm till now asking at 3am..

Thanks guys or girls!

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First JavaScript</title>
</head>
<body>
<script>
var drinks = "Energy Drink";
var lyrics = "";
var cans = 99;
    while (cans > 0) {

      lyrics = lyrics + cans + " cans of " + drinks + " on the 
      wall <br>";
      lyrics = lyrics + cans + " cans of " + drinks + "<br>";
      lyrics = lyrics + " Take on down pass it around, <br>";
      
      if (cans > 1)
        {
        lyrics = lyrics + (cans-1) + " cans of " + drink + " on 
        the wall <br>"
        }

     ** else *This is where my error seems to come from????*
        {
        lyrics = lyrics + "No more cans of " + drink + " on the 
        wall <br>";
        }
      cans = cans - 1;
    }
    document.write(lyrics);
</script>

</body>
</html>

Solution

  •   var drinks = "Energy Drink";
      var lyrics = "";
      var cans = 99;
      while (cans > 0) {
    
        lyrics = lyrics + cans + " cans of " + drinks + " on the wall <br>";
        lyrics = lyrics + cans + " cans of " + drinks + "<br>";
        lyrics = lyrics + " Take on down pass it around, <br>";
        
        if (cans > 1) {
          lyrics = lyrics + (cans-1) + " cans of " + drinks + " on the wall <br>";
        } else {
          lyrics = lyrics + "No more cans of " + drinks + " on the wall <br>";
        }
        cans = cans - 1;
      }
      document.write(lyrics);
    
    

    You did newlines in vars.

    You writed drink instead of drinks

    Change <script> by <script type="text/javascript">