You are on page 1of 10

JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

Brighten Up That Dull Old HTML

JavaScript
Tutorial:
Variables and
Operators
Explained
by Jon Perry

As you surf the Internet, you will notice sites do


things that seem impossible with HTML. They have
animated pictures, they validate forms for correct
Site Search
input, and change content according to users'
requests. They perform sums and play games.
April 12, 2000
A JavaScript tutorial
aimed at beginners,
or intermediate ● Part 2: Object Properties and Flow Control
users with a
hangover who
● Part 3: Functions and Classes
suddenly forget how
to turn numbers into
strings and These web pages are created using JavaScript, which is a
increment their language designed to work with HTML to improve and
variables. Includes enhance a web page
working code
examples for
HTML can create web pages and provides a basic
comparison, logical,
functional interface for the Internet. But writing it is like
compacted and
other operators. painting by numbers, and viewing it is like staring at
cardboard.
Javascript Articles:
JavaScript provides all the features of a fully
● Using comprehensive object-orientated, event driven language,

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (1 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

JavaScript To such as Java or C++, and allows direct access to the HTML
Control Forms document. Its advantages over these languages are that it
is simple to write and simple to deploy. It doesn't need
anything special to be added to a browser, and doesn't
● JavaScript need any specialist software for its creation.
Tutorial:
Variables and In fact, if you have a Text Editor and a browser, you can
Operators write some JavaScript right now.
Explained
JavaScript is contained within an HTML document. For
example:
● Ask the
JavaScript
<HTML>
Weenie
<HEAD>
<TITLE>My First JavaScript Program</TITLE>
● JavaScript
<SCRIPT>
Discussion
document.write('My First JavaScript Program');
Forum
</SCRIPT>
</HEAD>
</HTML>
● JavaScript
Mailing List When you save this, remember to save it with an .htm or
.html extension.

When the program is run, we see 'My First JavaScript


Program' printed on the screen, without any HTML text in
HOW DID THEY sight.
DO THAT???

Find out in: The JavaScript is contained within the <SCRIPT> tags.
Amazing HTML When the browser interprets this document, it thinks
'Hmmm, this is an HTML document, titled 'My First
JavaScript program', including some JavaScript -
'document.write ('My First JavaScript Program')'. Well, I
Site Map better execute this. And so it does.

Object-Orientated
Check out our Web- An object-orientated programming language (OOPL) is a
based system of keywords that perform varying actions. These
Discussion Groups:
keywords interact with internal data structures, known as
Web Development
objects, and with the computer itself.
Yak & Learn
The name object-orientated may throw you a bit. To
Check out and join our
understand it, stop what you are doing for a while and
email-based Mailing
Lists for Web
take a look around at reality. You are quite willing to
developers.
accept reality in terms of objects; there are people, cars,
computers, books, chairs, shoes, pens, haircuts, birds, etc.
Your Email
Each of these objects can be further divided, there are tall
Join List people, short people, red cars, blue cars, PCs and Macs,
and so on.

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (2 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

Developer Each of these objects does things. People talk or walk, cars
Channel go forwards or backwards, birds fly, etc.
FlashKit
Gif.com So, logically, when we try to model reality on a computer,
Jobs.webdeveloper we create objects.
JavaBoutique
The characteristics of an object are called properties, for
JavaScript.com
example (height, color, make), and the specific nature of
JavaScriptSource
each property is called a value (tall, red, PC).
JustSMIL
ScriptSearch The actions of an object are called methods (talk, drive,
Streaming Media fly).
World
VoiceXML Planet OOPLs also involve events. An event is something that
WDVL happens, so for example, a bird could land on a branch or
WebDeveloper.com a haircut could change.
WebReference
XML101 Variables
The most basic computer programming term is a variable.
A variable can hold whatever we want it to.

If we want to store our height, we would write:

myHeight='6 foot';

If we want to store our wealth, we would write:

money=100;

myHeight is known as a string, because it contains letters,


and money is a obviously a number.

We need to be able to display the contents of a variable.


There are several ways of doing this, but we shall begin by
using document.write, which we have already met.

document.write(xxxx) writes the value of xxxx to the


current document. xxxx may contain dynamic data, i.e. a
variable.

So,

<HTML>
<HEAD>
<TITLE>JavaScript Variables</TITLE>
<SCRIPT>
money=100;
document.write('You have '+money+' dollars to spend.');
</SCRIPT>

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (3 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

</HEAD>
</HTML>

This program displays 'You have 100 dollars to spend.'.

JavaScript is known as a loosely-typed language, which


means we don't have to declare whether our variable is
string type or integer type. This is both a blessing and a
curse.

We could write:

myHeight='6 foot';
myHeight=7;

This is legal in JavaScript. Equally:

money=100;
money='Fifty Quid';

is also legal.

We can change the value of a variable whenever we want


by resetting it. Here's a program that does just that.

<HTML>
<HEAD>
<TITLE>Changing Variables</TITLE>
<SCRIPT>
money=100;
document.write('You have '+money+' dollars to
spend.<BR>');
document.write('You spend 50 dollars.<BR>');
money=50;
document.write('You have '+money+' dollars to spend.');
</SCRIPT>
</HEAD>
</HTML>

The <BR> tags demonstrate the close link between HTML


and JavaScript. We can use JavaScript to write HTML to a
web page, in this case we write <BR> to force a line-
break, and neatly present the story.

We can display string variables in a similar way. This


program produces exactly the same output as the previous
one.

<HTML>
<HEAD>

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (4 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

<TITLE>Changing Variables 2</TITLE>


<SCRIPT>
money='100 dollars';
document.write('You have '+money+' to spend.<BR>');
money='50 dollars';
document.write('You spend '+money+'.<BR>You have
'+money+' to spend.');
</SCRIPT>
</HEAD>
</HTML>

But this is too simple, and it is also too clumsy. To model


real life, we need more flexibility with our variables. We
might not always spend 50 dollars - we might not even be
American!

This introduces the next section of JavaScript, the


operator.

Operators
An operator acts upon a variable and changes its value.
This offers more control than manually setting a variable
ourselves.

Basic Operators

Basic JavaScript operators include:

+ Addition/String addition
- Subtraction
* Multiplication
/ Division
% Modulus

Most operators are mathematical, i.e. they only work on


number variables.

Use of operators is generally very easy. If you study the


financial package offered below, you can see the
mathematical line is money=money-spend. The + signs
scattered elsewhere in the code we'll look at in a moment.

<HTML>
<HEAD>
<TITLE>Money Manager</TITLE>
<SCRIPT>
money=100;
document.write('You have '+money+' dollars to

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (5 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

spend.<BR>');
spend=50;
money=money-spend;
document.write('You spend '+spend+' dollars.<BR>You
have '+money+' dollars to spend.');
</SCRIPT>
</HEAD>
</HTML>

(Run the program) Try changing the values of money and


spend to get different results. You will also notice how we
must use numbers for the variables rather than strings if
we want to use operators on them. This is typical, strings
do not readily yield to subtraction, '100 dollars' - '50
dollars' is fairly meaningless to a computer because there
are letters involved.

We can perform string addition though. Here we combine


two strings with a character space between them:

<HTML>
<HEAD>
<TITLE>Message Maker</TITLE>
<SCRIPT>
greetings='Hello';
name='Jon';
document.write(greetings+' '+name);
</SCRIPT>
</HEAD>
</HTML>

Numbers can also be multiplied and divided. Our final


operator, the percentage sign, performs modulo
arithmetic, which means that the number returned is the
remainder after whole number divisions are done.

<HTML>
<HEAD>
<TITLE>Divide</TITLE>
<SCRIPT>
x=10;
y=3;
document.write(x/y+'<BR>'+x%y);
</SCRIPT>
</HEAD>
</HTML>

(Run the program) 10/3=3.333, but 10%3=1 which is the


remainder after 9 (3*3) has been removed.

If your computer displays something like

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (6 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

3.3333333333333335, instead of 3.3333333333333333 as


you would expect, don't worry, this is the oft-mentioned
floating-point bug rearing its head. Floating-point
arithmetic is generally very accurate, but does get it wrong
once in a while.

Variables names often end up short and meaningless. One


advantage of this is speed. Whenever a variable is used by
the computer, the entire variable name needs to be passed
around the system. It is quicker to pass 'x' than it is to
pass 'variablerepresentingten'.

A problem with operators occurs when we mix variable


types. What are we to do with a programming instruction
such as 'Jon'+1.

JavaScript will not give an error here, instead it will return


'Jon1' as a string. 1+'Jon' becomes the string '1Jon'.

'3'*1 gives the number 3, which is useful is we wish to


treat a string as a number.

''+1 gives the string '1', which is useful is we wish to treat


a number as a string.

Compacted Operators

The following operators are compactions of these basic


operators.

Addition/String addition with


+=
Assignment
-= Subtraction with Assignment
*= Multiplication with Assignment
/= Division with Assignment
%= Modulus with Assignment
++ Pre/Post Increment
-- Pre/Post Decrement

An operator with an equals sign applies the right hand side


to the left hand side of the expression, and stores the
result in the left hand side variable.

From the Money Manager program, we could have written:

money-=spend;
This code means exactly the same as:

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (7 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

money=money-spend;

Similarly, x=x*y; becomes x*=y; and so on.

Pre-/Post- Operators

The pre/post operators are a different kettle of fish.

They do have a simple use, to add or subtract one from a


number.

e.g. if x=5; then x++ makes x=6;

The difficulty lies in the various places these operators can


be used, and in understanding the difference between pre-
and post- incremention (or decrementation).

This is best seen with an example.

<HTML>
<HEAD>
<TITLE>Pre/Post Operators</TITLE>
<SCRIPT>
x=10;
y=10;
document.write('x is '+x+++', and now x is '+x);
document.write('<BR>y is '+--y+', and now y is '+y);
</SCRIPT>
</HEAD>
</HTML>

Confusing, hey?

Let us examine this slowly, and begin with x.

x starts its life as 10, and is written to the document.


Because we have x++, x is post-incremented, and now x
is 11, which we write again.

y also starts its life as 10. But we are pre-decrementing y.


So the pre-decrement acts on the y before it is printed, so
we write 9 to the document. y doesn't change after this, so
we write 9 again.

+x+++ and +--y+ are not immediately obvious


statements! Put the signs before the variable and it
immediately changes. Place them after and it changes
afterwards.

Comparison Operators

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (8 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

The comparison operators can be used to determine


relative values of variables.

< Less than


<= Less than or Equal to
> Greater than
>= Greater than or Equal to
!= Not Equal to
== Equal to

Use of these operators involves flow controls, which control


the program's flow.

We can see one of them in action, involving the Boolean


type of variable, which either returns true or false.

<HTML>
<HEAD>
<TITLE>Boolean</TITLE>
<SCRIPT>
document.write(4>5);
</SCRIPT>
</HEAD>
</HTML>

4>5 is a false statement, and equates to the false variable.

We could do this with any comparison operator to get


either a true or false value.

Logical Operators

The logical operators perform logical operations on


variables.

&& Logical AND


|| Logical OR
! Logical Negation
?: Ternary Operator

This is not a complete list of operators, just the essential


ones.

● Part 2: Object Properties and Flow Control

● Part 3: Functions and Classes

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (9 of 10) [08/04/2003 15:30:25]


JavaScript Tutorial: Variables and Operators Explained - The Web Developer's Journal

● More articles on JavaScript

Jon Perry is a Freelance Author and Programmer from the


UK.

Contact WDJ • Suits! • Propheads! • Ponytails!


Discuss • Subscribe • Search

internet.com
Internet News Internet Investing Internet Technology Windows Internet Tech. Linux/Open
Source Web Developer ECommerce/Marketing ISP Resources ASP Resources Wireless
Internet Downloads Internet Resources Internet Lists International EarthWeb Career
Resources Search internet.com Advertising Info Corporate Info Newsletters E-mail
Offers
internet.commerce
">Be a Commerce Partner Windows Web Hosting MLM Leads Submit Your Site AIIM
Exhibits-Free Build Flash Online Software Store Free Search Traffic

Copyright 2003 Jupitermedia Group, Inc. All Rights Reserved. Legal Notices, Licensing, Reprints, & Permissions, Privacy
Policy.

http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html (10 of 10) [08/04/2003 15:30:25]

You might also like