I am new to JavaScript environment.I have read that <script> </script> tag can be placed either in the <head> </head> or <body></body> tag of the document. But when I place <script> tag under the <head></head> the output is different. Please review the code:-
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
</head>
<body>
<p>This example calls a function which perfoms a calculation, and returns the result:</p>
<p id="demo"></p>
</body>
</html>
Output:- This example calls a function which performs a calculation,
and returns the result:
Whereas if <script></script> is placed under <body></body> then I get a different Output. Please find the code and the following output:-
<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which perfoms a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
</body>
</html>
Output:-
This example calls a function which perfoms a calculation, and returns
the result:12
Any help is highly appreciated.
When the following line of code runs, it searches the DOM for an element with the given ID:
When that code is in the
head, that element will not yet exist, and therefore the code will fail. When the code is in thebody(after the element in question), it obviously does exist and can be found.You could use a DOM ready event handler of some description in your script if you want to keep it in the
head. But “best practice” says to place scripts at the bottom of thebody.In your case, this is the effect you would see depending on the location of your script:
Note, however, that your function declaration could go anywhere, since it doesn’t do anything before it’s invoked. The invocation is the only part that will have to run after the element exists in the DOM.