0

I am newbie with javascript and I wrote a very simple program to test a while loop. My problem is, I do not know how to do line break with my code. Here is my code

<!DOCTYPE html>
<html lang="en">
<head>
<title>Phrase-o-matic</title>
</head>
<script type="text/javascript">
var scores = [60, 50, 53, 55, 61, 51, 44];
var output;
var i = 0;
while (i < scores.length) {
  output = "Bubble solution #" + i + " score: " + scores[i] ;
  document.write(output);
  i = i + 1;
}
</script>
<body>
</body>
</html>

As you can see, very simple. But, when I ran my code, it was no line break. It was very ugly. Could you please give me some ideas to repair it or more? Thank you very much.

2 Answers2

0

<!DOCTYPE html>
<html lang="en">
<head>
<title>Phrase-o-matic</title>
</head>
<script type="text/javascript">
var scores = [60, 50, 53, 55, 61, 51, 44];
var output;
var i = 0;
while (i < scores.length) {
  output = "</br> Bubble solution #" + i + " score: " + scores[i] ;
  document.write(output);
  i = i + 1;
}
</script>
<body>
</body>
</html>
0

There's no need to assign a value to the output variable since you're not using it.

Use let or const instead var read more about it here: https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/

Template literals are much cleaner than concatenation read more about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Try this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Phrase-o-matic</title>
  </head>
  <script type="text/javascript">
    const scores = [60, 50, 53, 55, 61, 51, 44];
    let i = 0;
    while (i < scores.length) {
      const output = `Bubble solution #${i} score: ${scores[i]} <br />`;
      document.write(output);
      i++;
    }
  </script>
  <body></body>
</html>
onlit
  • 728
  • 5
  • 19