Introduction to JavaScript

How do we use JavaScript?

There are two ways of adding JavaScript to our HTML pages. The simplest alternative is to put our code inside <script> tags and put it somewhere within the <html> tags. The last alternative, which is also the most commonly used one, is to write our scripts in separate .js files and reference said files in our <head> element.

Script tag

Putting all of our JavaScript code inside a <script> tag works for smaller pieces of code and smaller projects, but can be hard to maintain for larger web sites. Another downside is that the HTML document sizes become larger because the same pieces of code is sent over the network for each page load. This can be avoided by referring to a JavaScript file in the <head> element which most browsers cache.

<script>
// we can write our JavaScript here
/* don't worry:
you are not supposed to understand
any of this yet
*/
const h2 = document.querySelector("#largeAndBold")
h2.addEventListener("click", (e) => {
console.log("I was clicked")
})
</script>
<h2 id="largeBold">
I am large and bold.
</h2>

Separate file

Writing all of our JavaScript code in separate .js files and referring to them using the <script>'s src attribute inside our <head> element is the most common way of including JavaScript in HTML pages. We avoid repetition, reduce network usage and improve maintainability.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Original title</title>
<script type="text/javascript" src='main.js'></script>
</head>
<body>
<h2 id="largeBold">
I am large and bold.
</h2>
</body>
</html>
// we can write our JavaScript here
/* don't worry:
you are not supposed to understand
any of this yet
*/
const h2 = document.querySelector("#largeAndBold")
h2.addEventListener("click", (e) => {
console.log("I was clicked")
})