<html> <header> <script>

function myFunction(p1, p2) {
    return p1 * p2;
document.getElementById("demo").innerHTML = myFunction(4, 3);   
</script> </header> <body> <div id="demo"></div> </body> </html>

I don't understand why the above code does not show any value?

and why this one does?


<html> <body> <div id="demo"></div> <script>
    function myFunction(p1, p2) {
return p1 * p2;
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script> </body> </html>

Why I cannot stated the js first then calling it? Why calling it first then stated the js?

5 Months
Discussion Span
Last Post by ryantroop

I think I see why. In program1 line 6 calls out an element "demo" and there is no such element.

Answer? "Bum code does nothing."


Javascript (JS) is a top down JIT. Which means if the DOM element exists before the JS gets called, it will be available for use.

In example 1, your function declaration and call happen before "demo" is available on the DOM (in the body element, however you want to think about it).

In example 2, the element is declared first, and therefore available for JS to use.

In the wild, you will see a lot of websites put code library or include type script at the very bottom of the page for 2 reasons.
1 - you load the HTML and the DOM displays to the user even if there is a network hiccup to the provider (akamai, or whatever)
2 - you are guranteed all elements are rendered and available on the page

That said, the "right" or "javascript" way of doing this is to have a window "onload" handler (window.addEventListener("load", fnYourFunction)) which will fire off all script after the DOM has finished loading and has parsed all elements.

Link for reference: https://developer.mozilla.org/en-US/docs/Web/Events/load

Edit ---

This leads to some of the wonky ways that JS uses DOM elements and references them. For example, in your example #2 you could have just put :

demo.innerHTML = myFunction(4, 3); //dont do this youll make people mad.

because all elements get referenced in the global scope of JS

Edited by ryantroop: more info

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.