JS First Program

Lets execute our very first JavaScript program. Create a file index.html and add following code in it.

<script type="text/javascript">  
        document.write("First Javascript program");  
   </script> 

  • The <script> tag indicates that we are using JavaScript inside HTML code.
  • “text/javascript” indicates browser about the data.
  • document.write() function is used to print text in the browser.

We can write JavaScript code using two different methods.

  • Including JavaScript Code in the HTML
  • Including external Javascript file in the HTML document.

Including JavaScript Code in the HTML
we can include javascript code inside HTML code using <script> </script> tags. see the below example.

   <!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
   </head>
   <body>
    
   //HTML Body

    <script>
     document.write("This js Jacascript code inside HTML file")
    </script>   
   </body>
   </html>

In above example we have included JS code inside HTML file using opening and closing script tags <script> </script>. When the HTML file is loaded the browser interprets the code written within script tags as JavaScript Code.

Below is the output of the above program.

This js Jacascript code inside HTML file

Including external JavaScript file in the HTML
we can write JavaScript code in a separate file with extension .JS and include this javascript file inside HTML code. See below example.

   <!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
   </head>
   <body>
    
    //HTML body

    <script type="text/javascript" src="external.js">
    </script>   
 

   </body>
   </html>


We can include external JS file in HTML using script tags. In above example we have included the file “external.js” which is placed in the same directory.
The included JS file will be interpreted by browser as JavaScript code.

We need to pass file path in the script tag src attribute. When we include external JS we need to hard reload the browser in order to render updated changes in the external JS file. If the JS code is included in the html then the browser is reloaded but in case of external JS file we need to Hard Reload the browser. Hard reload clears the cache and interprets the external JS code again so that gets executed in the browser.

About the Author: allcodebuzz

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *