Javascript Introduction



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.