Ways to execute JavaScript

There are three ways of executing JavaScript on a web browser.

1. Inside <HEAD> tag
2. Within <BODY> tag
3. In an External File

1. Inside <HEAD> tag

Example : Simple JavaScript Program using <HEAD> tag

head.html          //File Name

<html>
     <head>
     <script type = "text/javascript">
     function abc()
     {
          document.write("CareerRide Info");
     }
     </script>
     </head>
<body>
     Click the button
     <input type=button onclick="abc()" value="Click">
</body>
</html>


Output:
inside head tag
CareerRide Info

2. Within <BODY> tag

Example : Simple JavaScript Program using <BODY> tag

body.html          //File Name

<html>
     <body>
     <script type="text/javascript">
          document.write("CareerRide Info");
     </script>
     </body>
</html>


Output:
CareerRide Info

3. External File

Example : Simple JavaScript Program using External File

external.html          //File Name

<html>
     <body>
          <script type="text/javascript" src="abc.js">
          </script>
     </body>
</html>

abc.js          //External File Name
document.write("CareerRide Info");


Output:
CareerRide Info

Rules for writing the JavaScript code

  • Script should be placed inside the <script> tag.
  • A semicolon at the end of each statement is optional.
  • The single line comment is just two slashes (//) and multiple line comment starts with /* and ends with */.
  • Use 'document.write' for writing a string into HTML document.
  • JavaScript is case sensitive.
  • You can insert special characters with backslash (\& or \$).