SniCel SniCel - 1 month ago 4
Javascript Question

Is this code from w3school correct?

i learn javascript from w3school. I got to this example. Is there any possibility how to write this code "better" ? Is it not antiquated?

Thank You

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arrays</h1>

<p>The best way to loop through an array is using a standard for loop:</p>

<p id="demo"></p>

<script>
var fruits, text, fLen, i;

fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Answer

I will suggest this

<!DOCTYPE html>
<html>
  <body>

    <h1>JavaScript Arrays</h1>

    <p>The best way to loop through an array is using a standard for loop:</p>

    <p id="demo"></p>

    <script>
      var fruits = ["Banana", "Orange", "Apple", "Mango"];
      var fVar = 0;
      var fLen = fruits.length;
      var htmlContent = "<ul>";
      for (fVar = 0; fVar < fLen; fVar++) {
        htmlContent += "<li>" + fruits[fVar] + "</li>";
      }
      htmlContent += "</ul>";
      document.getElementById("demo").innerHTML = htmlContent;
    </script>

</body>
</html>

This is just a basic code to understand the Array concept nothing more.

Comments