Javascript Introduction
JavaScript is a flexible language, that is used predominantly for the Web development.
It is one of the means developers use to add features such as reactions to user actions and dynamic content to websites. As opposed to this, HTML is responsible for the structural features, CSS - for styling, and JS - is in charge of the interaction and behavior of the website pages.
Now, let's dive into a simple example of a "Hello, World!" program in JavaScript. You can include JavaScript code directly within HTML files or in separate .js files.
Let's see an example within an HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello, World!</title>
</head>
<body>
<script>
// JavaScript code goes here
alert('Hello, World!');
</script>
</body>
</html>
In this example, the <script> tags are used to enclose the JavaScript code. The alert('Hello, World!'); statement displays a pop-up alert with the message "Hello, World!" when the page loads.
You can also create a separate JavaScript file. Save the following code in a file with a .js extension, for example, script.js:
// script.js
alert('Hello, World!');
Then, include this file in your HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello, World! Example</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
This module holds the content of HTML, but the JavaScript does not bother this module, resulting in a better structure and cleaner and more maintainable code. The src attribute of <script> refers the node to an external JavaScript file.