JavaScript Where To

In HTML, You can write JavaScript code between script tag or into separate .js file to execute JavaScript code.

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

Example :

 <script>
document.getElementById("demo").innerHTML = "Hello World";
</script>

JavaScript in <head> Tag

JavaScript code can be placed in the <head> section of an HTML page.

Example :

 <!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>

<p id="demo"></p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

JavaScript in <body> Tag

JavaScript code can be placed in the <body> section of an HTML page.

Example:

 <!DOCTYPE html>
<html>
<body>

<h2>JavaScript in Body</h2>

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

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World.";
}
</script>

</body>
</html> 

External JavaScript

Scripts can also be placed in external files:

script.js external file:

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World.";
}

To use an external script, put the name of the script file in the src attribute of a <script> tag:

How to include external js file:

<script src="script.js"></script>