Ways of adding javascript code to HTML 
Basically, we have two ways of adding javascript code to HTML.
  1. Internal JavaScript
  2. External JavaScript
1. Internal javascript: We can add javascript code in HTML internally on the <head> section or on the <body> section of an HTML page.
The script tag: The script tag is used to add javascript code internally to an HTML page.
<script> javascript code goes here...</script>
Example1: JavaScript in the <head >section
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("j2").innerHTML = "JavaScript in head.";
}
</script>
</head>
<body>
<p id="j2">JavaScript.</p>

<button type="button" onclick="myFunction()" >Click me!</button>

</body>
</html> 
Output

JavaScript.


Example2:
JavaScript in the <body> section
<!DOCTYPE html>
<html>
<head>

</head>
<body>
<p id="j3">JavaScript.</p>
<button type="button" onclick="myFunction()" >Click me!</button>

<script>
function myFunction() {
  document.getElementById("j3").innerHTML = "JavaScript in body.";
}
</script>
</body>
</html> 
2. External JavaScript: JavaScript can also be used as an external file with file extension .js.
To use external javascript insert the name of the javascript file inside the src(source) attribute of the script tag as follows.
<script src="Script_name.js"></script>
Example3: JavaScript as an external file
JavaScript code with filename (myscript.js)
function myFunction() {
  document.getElementById("j2").innerHTML = "JavaScript as external file.";
Now, The External script file must be added to the src attribute as follows.
<script src="myScript.js"></script>
Finally, Insert the above script in Either the <head> section or the <body> section of the HTML file as you want, as follows.
<html>
<head>
<script src="myScript.js"></script>
<!DOCTYPE html>
</head>
<body>
<p id="j4">JavaScript.</p>

<button type="button" onclick="myFunction()" >Click me!</button>

</body>
</html>