JS First Example



A. First JS Code :

<html>
<body>

<h1>Our First JS Code</h1>

<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>

</body>
</html>

Try it Yourself »

Output :

First JavaScript Program

Basic Tags and Attributes Explained !!!

Tag Attribute Meaning
html - html Contains the HTML part of the Web page
head - Contains the header part of the Web page
script - Contains the Web page’s script or a reference to the external script file
src The location of an external script
title - Contains the title of the Web page
body - Contains the body part of the Web page

Explanation :

Starting <script> :

  1. Opening script tag.
  2. Tells the browser to expect JavaScript instead of HTML.

Print Text in JS :

document.write("<p>" + Date() + "</p>");
  1. First line of JavaScript.
  2. It takes the document window and writes current date into document.
  3. Note the semi-colon at the end of the line this tells the browser’s JavaScript interpreter that the line is ending.
  4. Semicolon is Optional

Ending </script> :

  1. Ends the JavaScript and tells the
  2. Browser to start expecting HTML again.

B. Hiding JS in older browsers :

<html>
<body>
<p>Date will not be displayed in older browsers</p>
<p id="demo"></p>

<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML = Date();
//-->
</script>

</body>
</html>

Try it Yourself »

Explanation of Above Code :

  1. All modern browsers supports JS.
  2. If any old browser that do not support JavaScript will show JS Script as its page content.
  3. In order to handle this situation JavaScript Standard provides us easy way of hiding JS code.
  4. HTML Comment tag is used to hide JS code.

How to Comment Code ?

  1. Add an HTML comment tag <!– before the first JavaScript statement
  2. Add a –> (end of comment) after the last JavaScript statement.
  3. The two forward slashes at the end of comment line (//) is the JavaScript comment symbol.
  4. This prevents JavaScript from executing the –> tag.