Javascript Reference Error

0

I think one of my biggest problems in javascript is the way I write what I do and I need a push if someone can why this happens to me:

I'm getting the following error:

  

Reference error: simplefor is not defined

The only thing I can think of is to do window.simplefor = function() , but I do not want to do it, I like to understand why I do this and really understand how it works , it is worth noting that I research a lot, I see videos, books and more.

// Simple for loop 1 - 10

function simplefor() {
  var i = 0;
  for (i; i < 10; i++) {

    document.write(i + '\n')

  }
}
<h1 style="text-align: center">Learning Javascript</h1>
<hr></hr>
<h5 style="text-align: center">Simple for 1 - 10 </h5>

<script>
  simplefor()
</script>

<hr/>
    
asked by Eduardo Sebastian 24.05.2017 в 14:23
source

2 answers

1

The problem is that the code editor, when assembling the page, includes the javascript code after the HTML code:

Therefore the call to the function is before the declaration of it.

The error gives you because you are trying to call a function that has not yet been declared.

You should try not to include javascript code directly inside your html code (like the call to the simplefor function).

Here is an example of how you could get the code. What I have done is to modify the simplefor function so that it receives as an argument the HTML element in which it must insert the text. In the HTML code I added a div in the place where I want the text to be added and I pass it in the call to simplefor:

// Simple for loop 1 - 10

function simplefor(containerElement) {
  var i = 0;
  var text = '';
  for (i; i < 10; i++) {
    text+= i + '\n';
  }
  containerElement.innerText = text;
}

var container = document.getElementById('content');
simplefor(container);
<h1 style="text-align: center">Learning Javascript</h1>
<hr></hr>
<h5 style="text-align: center">Simple for 1 - 10 </h5>

<div id="content"></div>

<hr/>
    
answered by 24.05.2017 / 16:22
source
1

It is necessary to include the function in the html code

<script>
  function simplefor() {
    var i = 0;
    for (i; i < 10; i++) {

      document.write(i + '\n')

    }
  }
</script>

<h1 style="text-align: center">Learning Javascript</h1>
<hr></hr>
<h5 style="text-align: center">Simple for 1 - 10 </h5>

<script>
  simplefor();
</script>

<hr />
    
answered by 24.05.2017 в 14:27