-3

So I am making this code assignment, and when I went to validate it, it seems the JavaScript wasn't being "called." So I checked my code. The HTML elements call the JavaScript okay, there are no typos, and I still haven't found the problem!

HTML

<html>
<head>
<title>Conditional statements and Loops</title>
</head>
    
<body>
<script type="text/javascript" src="pattern_javascript.js">
</script>
</body>
</html>

JS

function loop() {
var asterisk = ["*", "**", "***", "****", "*****", "******", "*******", "********"];
var text = "";
var i;
for (i = 0; i < asterisk.length; i++) {
text += asterisk[i] + "<br>";
}
}

loop()
halfer
  • 18,701
  • 13
  • 79
  • 158

2 Answers2

1

You define and populate several local variables, then discard them all without displaying anything. You possibly want a return statement:

function loop() {
  var asterisk = ["*", "**", "***", "****", "*****", "******", "*******", "********"];
  var text = "";
  var i;
  for (i = 0; i < asterisk.length; i++) {
    text += asterisk[i] + "<br>";
  }
  return text; // <------------
}

document.querySelector("section").innerHTML = loop();
<section></section>
Álvaro González
  • 128,942
  • 37
  • 233
  • 325
  • Hey! I found a solution, and I am marking this the correct answer since it is similar. I replaced the console.log with a document.write and it is now displaying. Thank you! – amateur_coder Jul 02 '20 at 15:39
  • 1
    @amateur_coder `document.write` is [not recommended](https://stackoverflow.com/q/802854/4642212) for DOM manipulations, as it is obsolete, slow and not suitable for any evolving application. – Sebastian Simon Jul 02 '20 at 15:41
  • 1
    This code does not satisfy the question asked here, As the user needs the text to be displayed on the HTML and not on the console. – Karthik Radhakrishnan Jul 02 '20 at 15:43
  • @user4642212 ok, I will try the other users answer. – amateur_coder Jul 02 '20 at 15:46
  • @KarthikRadhakrishnan The question didn't state anything like that. Such new requirement was made afterwards in some followup comments. I'll update the answer anyway. – Álvaro González Jul 02 '20 at 17:46
0

The value of text is being generated properly. However you need to use the text somewhere in the html

function loop() {
var asterisk = ["*", "**", "***", "****", "*****", "******", "*******", "********"];
var text = "";
var i;
for (i = 0; i < asterisk.length; i++) {
text += asterisk[i] + "<br>";
}
document.getElementById("demo").innerHTML=text;
}

loop()

HTML

<html>
<head>
<title>Conditional statements and Loops</title>
</head>

<body>
<p id="demo"></p>
<script type="text/javascript" src="pattern_javascript.js">
</script>
</body>
</html>

Ref: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid