JS stands for ‘JavaScript’.
It is a high-level programming language.
It is one of the three core technologies of the World Wide Web, alongside HTML (for structure) and CSS (for styling) and JS adds interactivity.
JavaScript enables content to be interactive and dynamic, turning static content into responsive content that can react to user actions like clicks, hovers, or input fields. It allows developers to update webpage content, control multimedia, animate graphics, validate forms, and handle user input directly in the browser.
Originally, JavaScript was designed to run directly in web browsers (client-side) using users' devices (computer, tab, mobile) and device's resources, enabling features like interactive forms, animations, dynamic content updates without needing full page reloads.
With the advent of Node.js, JavaScript can also be used on the server-side using server’s resources, allowing developers to build full-stack applications using a single language. This includes tasks like managing databases, handling user authentication, and processing data.
Analogously, if HTML builds a car and CSS paints it then JS adds user interactivity and motion to the car.
Three ways to add JS to an HTML document -
1 Inline JavaScript -
JavaScript can run directly from HTML element attributes, such as onclick, onmouseover, etc.
Code -
<!DOCTYPE html>
<html>
<head>
<title>The title</title>
</head>
<body>
<h1>Welcome!</h1>
<button onclick="alert('This is inline JavaScript');">Click this</button>
</body>
</html>
2 Internal JavaScript -
Using the <script> tag JavaScript can be embedded in HTML documents.
Code -
<!DOCTYPE html>
<html>
<head>
<title>The title</title>
<script>
function greet() {
alert("Hello!");
}
</script>
</head>
<body>
<h1>Welcome!</h1>
<button onclick="greet()">Click this</button>
</body>
</html>
3 External JavaScript -
Create a separate file with a .js extension (e.g., script.js).
Write the JavaScript code within this file.
Link this file to the HTML document using the <script> tag with the ‘src’ attribute, by typing the path or URL of the JavaScript file.
Code -
<!DOCTYPE html>
<html>
<head>
<title>The title</title>
</head>
<body>
<h1>Welcome!</h1>
<script src="script.js"></script>
</body>
</html>
JavaScript code to print ‘Hello World’ where output is accessible through the browser console -
console.log("Hello World");