JavaScript introduction

The script tag

The first thing you need to do is to add a script tag to the head of your document.

Direct JavaScript

You can enter JavaScript directly inline with your HTML using the script tag.

<head>
   <script language="javascript" type="text/javascript">
   <!--

   -->
   </script>
…

Linking to a document

You can also write all your code into a separate document with the .js file type and link to it in your document.

<head>
   <script type="text/javascript" src="mycode.js"></script>
…

Declaring variables

To declare a variable in JavaScript prefix the name of the variable with the code var.

<script language="javascript" type="text/javascript">
<!--
   var myVariable = 'string';
   var myNumber = 0;
   myNumber = myVariable;
-->
</script>

The example above shows you how to declare a variable and also that you do not need to declare a type for your variable. A variable can change its type throughout the script.

Declaring arrays

To declaring an array use the following code.

var myArray = new Array();
myArray[0] = 0;
myArray[3] = 'string';

This example shows you that arrays can contain different data types and do not need to have a size declared.

Writing functions

The example below shows you how to write a simple function.

function MyFunction(parameter1, parameter2)
{
	return parameter1 + parameter2;
}

Categories

Tags

Social