Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
JavaScript - Basic Structure
Closures in JavaScript
Using CSS in Javascript
OOPS in Javascript
Popup Window in Javascript
Printout a page in Javascript
Variable declaration in JavaScript
Difference of let, var and const
JavaScript - JSON Parse & Stringify

JavaScript - Basic Structure



Here is the basic structure of a simple JavaScript program that outputs a message to the console:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic JavaScript Example</title>
    <script>
        // This is a simple JavaScript program
        function showMessage() {
            // Output a message to the console
            console.log("Hello, World!");
        }

        // Call the function to show the message
        showMessage();
    </script>
</head>
<body>
    <!-- Content of the HTML document -->
</body>
</html>

Explanation of Each Component

  1. HTML Structure:

    • The <!DOCTYPE html> declaration defines the document type and version of HTML.

    • The <html> tag is the root element of an HTML document.

    • The <head> section contains meta-information about the document, such as the character set, title, and embedded JavaScript.

    • The <body> section contains the content of the HTML document.

  2. JavaScript Code:

    • The <script> tag is used to embed JavaScript code within the HTML document.

    • function showMessage() {}: Defines a function named showMessage.

    • console.log("Hello, World!");: Outputs the string "Hello, World!" to the browser's console.

    • showMessage();: Calls the showMessage function to execute the code within it.

External JavaScript File

Instead of embedding JavaScript directly within the HTML file, you can also include an external JavaScript file. Here' how you can do it:

  • Save the JavaScript code in a separate file, for example, script.js.

javascript
// script.js
function showMessage() {
    console.log("Hello, World!");
}

showMessage();
  • Reference the external JavaScript file in the HTML document using the <script> tag with the src attribute:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External JavaScript Example</title>
    <script src="script.js"></script>
</head>
<body>
    <!-- Content of the HTML document -->
</body>
</html>

The external JavaScript file is included in the HTML document and will be executed when the page loads. This approach is preferred for better organization and maintenance of your code.

JavaScript is incredibly versatile and can be used for much more than simple output. If you'd like, I can show you more advanced examples or specific functionalities




All rights reserved | Privacy Policy | Sitemap