Introduction to JavaScript

JavaScript allows you to create dynamic and interactive web pages. It is an object-based scripting language, which was developed by NetScape in 1995. Java and JavaScript are not relatated. The official name for JavaScript is "ECMAScript".


Syntax

<script type="text/javascript">

Statement goes in here

</script>


In HTML5 you can omit the
type ="text/javascript"



Add JavaScript Code

There are three ways to add JavaScript code on a web page:

  1. In the Head Section
  2. As an Inline Script (within the body tag)
  3. As an External File


Head Section

The script tag is placed inside the <head></head>. Have a look at the example below; the function called add is inside the<head></head>, which is executed when the button inside the <body></body> is clicked.


Example

<head>
<script>
function add()
{
var a=3;
var b=9;
var c=a+b
alert("Answer="+c) }
</script>
</head>

<body>
<p>3+9=?</p>
<input type="button" onclick="add()" value="Ans"/>
</body>





Displays

3+9=?




Inline Script

The JavaScript codes are embeded into the HTML content. The example below shows the <script></script> inside the <body></body>.

Example


<body>
<script>
document.write("Welcome to Lilly Robot");
</script>
</body>

Displays




External File

An external file contains nothing but JavaScript codes. The document is saved with a file name followed by the extension .js. You can then call the JavaScript file on the HTML page inside the <head></head>. An external file is useful if you want to save time in writing repetative codes on several pages.


Example

<head>
<script src="documentName.js"> </script>
</head>




Comment

It is good practice to write comments about your JavaScript code. The comments cannot be seen on the browser. It helps you understand when the code was written, who wrote the code and what the code does.

The two types of comments are:

  1. // The double slashes represent a single line comment
  2. /* Start of multi line comments

    */ End of multi line comments
<script>

// This is my single line comment

/* This is my multi line comment - very useful if I want to write a few things about what my code is suppose to do. */

</script>



Things to know




Now do the Exercise!