Javascript/Actionscript: Variables and Basic Operators

 

The use of variables in combination with the basic operators is how a lot of work gets done in a computer program. We will breifly review how to declare and use a variable, and a list of the more commonly used operators. To ultimately understand this, you will need to review the examples contained in the first Javascript Tutorial.

The following is generally true of both Javascript and Actionscript. In the text below, when referring to Javascript, I mean BOTH Javascript and Actionscript.

 

 

Variables

 

A variable is a temporary place in computer memory which is named and can be used to place a numeric value, piece of text, etc. until it is needed later. You can think of each variable as a specific "container" the size of whatever you need to store there, and with a name you can use to find it again later. In most computer programs, variables are used to represent physical values of things in the real world - for instance the distance of an object visible on the screen from the top of the browsers window, or the number of seconds the user has been looking at this particular window. While Javascript is pretty forgiving about the way variables are created - the best way to create a variable is to declare it:

 

var x; /* create a variable x */
var windowHeight, windowWidth; /* create two variables windowHeight and windowWidth */

var delayTime = 100;

/* create the variable delayTime and put the value 100 in it - this is called initializing the variable */

 

 

Operators

 

Operators exist for working with both numbers and with text. Some operators do both, and work in different ways with text than they do with numbers.

 

Arithmetic / Text string operators

x + y (Numeric) Adds x and y together
x + y (Char. String)

concatenates x and y together ( creating a new string that is x immediately followed by y)

x - y subtracts y from x
x * y multiplies x by y
x / y divides x by y
x % y returns x modulo y - the remainder after x is divided by y
x++ or ++x increment x by 1 (same as x = x + 1)
x-- or --x decrement x by 1 (same as x = x - 1)
-x reverse the sign of x

 

Assignment

x = y Sets value of the variable x to the value of (variable or literal) y
x += y

same as x = x + y

x -= y same as x = x - y
x *= y same as x = x * y
x /= y same as x = x / y
x %= y same as x = x % y

 

Comparisons

Comparisons are used to return a Boolean value of true or false depending on whether or not the statement given is true or false.

x == y returns true if x and y are equal
x != y

returns true if x and y are not equal

x > y returns true if x is greater than y
x < y returns true if x is less than y
x >= y returns true if x is greater than or equal to y
x <= y returns true if x is less than or equal to y
x && y returns true if x and y are both the Boolean value true
x || y returns true if either x or y are the Boolean value true
!x returns true if x is the Boolean value false