JavaScript Variables and Operators

Operating on Variables

So far we have looked at how to create variables. This doesn’t achieve very much unless we can also use and update the values stored in those variables. To update the values stored in variables we use operators.

Never mind the fancy name. You are already familiar with many of the operators.

Numerical Operators

Let's start by looking at the operators that allow us to work with numbers and variables that contain numbers and you will see exactly what I mean.

1 left + right
2 payment - change
3 width * height
4 pie / people
5 selection % choice
6 counter++
7 ++counter
8 counter--
9 --counter

These nine examples show the different ways that you can operate on one or two variables (or a variable and a number) to determine a new value based on the original values.

The first four of these are rather obvious, as you have probably guessed they add, subtract, multiply, and divide respectively. What isn't so obvious is that the result of that calculation doesn't actually update either of the variables in the calculation, instead it returns the value calculated. We need to assign the result to a variable (with =) if we need to keep it for later use.

When you got to the fifth operator your probably had no idea what that percent sign (%) means. Everyone knows what + (plus), - (minus), *(the computer version of the multiplication sign) and / (the computer's division symbol) mean, but what sort of operator is %? Well actually it relates to division and is known as the remainder, or modulo operator. If the value in pie were 11 and the value in people were 3 then the result of pie % people would be 2 – the remainder from the division of the second number into the first.

The last four examples are different from the first five in that they actually change the value contained within the variable. Both counter++ and ++counter add one to counter while counter-- and --counter subtract one from counter. The placement of the ++ or -- either in front or behind only make a difference if you combine these operations with others in the same statement.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow