Introduction
This article provides a
basic overview of JavaScript programming. It's assumed that the reader
has a basic knowledge of HTML and either C or C++. You can get a brief
overview of C++ programming here.
HTML
HTML stands
for HyperText Markup Language and is the main language used for the creation
of web pages. HTML is used to describe the appearance of text-based
information on a webpage (such as headings, paragraphs, lists, and so on) as
well as supplementing the text in a page with interactive forms, embedded
images, and so on. In addition, HTML can include embedded code from
scripting languages such as JavaScript to further enhance the functionality
of a webpage. A web browser interprets HTML code.
A HTML file is a text file with either a .htm or .html filename extension.
As such, HTML files can be created in NotePad or using web development
software such as Microsoft FrontPage.
JavaScript
JavaScript is
a scripting language with a syntax loosely based on C. A scripting language
is a computer programming language that’s typically typed directly from a
keyboard and interpreted. Scripts are often distinguished from programs in
that programs are normally compiled (converted into binary executable files)
before they are run.
A JavaScript
engine relies on a host environment (normally web-based) into which it is
embedded. One major use of web-based JavaScript is to write code and
functions that are embedded in (or included from) HTML pages. In this
application the script interacts with the Document Object Model (DOM) of the
page to perform tasks not possible in HTML alone.
Writing JavaScript
JavaScript is
normally embedded in the heading <head> or body <body> sections of a HTML
page. Consider the following example:
<head>
<script type = "text/javascript">
<!--
document.writeln("Hello");
//-->
</script>
</head>
There is only
one line of JavaScript code in this example shown in bold text. The
JavaScript code is placed between the <script> and </script> tags. The <!-
and //--> tags merely make the JavaScript code look like a HTML comment for
older browsers that cannot interpret JavaScript.
JavaScript is a case-sensitive language like C and C++.
Text output
The writeln function
is used to write and entire line of text to the webpage followed by a
carriage return. The write function does a similar job without adding a
carriage return. Below are some examples.
Normal line
output:
document.writeln("Hello");
Embedded HTML
tags:
document.writeln("<h1>Hello</h1>");
document.writeln("Hello<br>");
Normal text
output:
document.write("Hello");
Normal text
output with concatenated strings:
document.write("Hello"
+ " there");
Alert (message box)
The alert function is used
to create a simple message box as shown:
window.alert("Welcome!");
Variables
JavaScript variables use
the same naming conventions as C and C++ only that the $ character can also
be used. Variables are preceded by the keyword var but do not require
a data type. Some variable declarations are shown below:
var count, weight, name;
Variables can also be
initialised during declaration as shown in the example below:
var count = 100;
Comments
Comments are
written in JavaScript as done in C using /* and */ or as in C++ using //.
Prompt boxes
Prompt boxes are like
interactive message boxes for receiving input from the user.
var age;
age = window.prompt("Please enter your age","0");
document.writeln("Your age is " + age + ".");
The "0" in the prompt
function is the default input value.
Converting string input to a
numerical value
The data received from a
prompt box is a string type. Therefore, it must be converted to a numerical
value before it can be used in any computation. An example is shown below:
var age, ageString, height, heightString;
ageString = window.prompt("Please enter your age","0");
heightString = window.prompt("Please enter your height","0");
age = parseInt(ageString);
height = parseFloat(heightString);
Arithmetic operators
The arithmetic operators in
JavaScript are the same as in C++. They include +, -, *, /, %, ++, --, +=
and so on.
Math object
The Math object can be called when more complex mathematical functions are required. These include abs(x), log(x), pow(x,y), sqrt(x), sin(x), random(), and so on. They’re used in the following way:
var x = 16, y;
y = Math.sqrt(x);
The math object also contains constants such as Math.PI, which represents the value pi.
Relational operators
The relational operators in JavaScript are the same as in C++: ==, !=, >, >=, <, <= and so on.
Boolean operators
The Boolean operators in JavaScript are the same as in C++, namely && (AND), || (OR), and ! (NOT).
Selection control structures
Selection control structures in JavaScript are syntactically the same as for C and C++ including if, else and switch.
Iteration control structures
Iteration control structures in JavaScript are syntactically the same as for C and C++ including while, do while and for loops. Control keywords break and continue also work in the same way.
Functions
Functions in JavaScript are preceded by the keyword function and are either placed below the main code or in the <head> section of the HTML code. An example is shown below:
function square(y)
{
return y * y;
}
Variable y is an argument passed to the function square.
Functions and HTML forms
Often you’ll want to call a function as a result of the user’s interaction with the HTML page, such as when they click a button. This can be done through HTML forms, which can contain input boxes and buttons.
You can create a button in the following way:
<form>
<input type = "button" value = "Calculate"
onclick = "calculate()">
</form>
In this example, “button” is the type of input type, “Calculate” is the name of the button, and “Calculate()” is the name of the JavaScript function we want to call when the button is pressed.
You can get an input box in following way:
<form>
<input name = "age" value = "0" maxlength = "15"
size = 15>
</form>
Here’s a program that converts inches to centimetres:
<head>
<script type = "text/javascript">
function Convert(form)
{
var cm = parseFloat(form.Inches.value)*2.54;
document.writeln(cm);
}
</script>
</head>
<body>
<form>
<input name = "Inches" value = "0" maxlength = "10" size = 10>
<input type = "button" value = "Convert" onclick =
"Convert(this.form)">
</form>
</body>
JavaScript arrays
Arrays in JavaScript are declared in the following way:
var numbers;
numbers = new Array(12);
Note the use of the new operator, the Array object, and the round brackets. Array elements are then accessed as numbers[0] to numbers[11] as in C and C++.
When passing an array to a function, simply use the array name as the argument without the square brackets as shown:
myFunction(myArray); // Function call
function myFunction(myArray) // Function definition
{
}
Note that in the function definition, you can use myArray or any other alias (name) for the passed array. As in C++, arrays are passed to functions by reference so any change to the array in the function affects the actual array.
Back to
top
|