JavaScript Variables and Operators

What Are Variables

"If you have your screen set to display 1024 by 768 pixels resolution then how many pixels are being displayed on the screen?" If you had to answer this question yourself without using a computer or calculator, you would probably need to write out the calculation on a piece of paper and work out intermediate results. You start by multiplying four by eight to give 32, and then work your way through the successive simple multiplications that you have memorized the answers to, writing down the various results. You then add the results of those simple calculations to get the final answer. With a really good memory, you may be able to do all the calculations in your head and get the answer of 786,432 without having to write down anything at all. Whichever way you work it out, the results of your intermediate calculations need to be stored somewhere, either on paper or in your head.

Perform this same calculation using a computer (that is, using a computer program or script) and the computer needs to remember the intermediate and final results in the same way that you or that piece of paper do. To be able to later retrieve those values without having to hunt all over the computer memory looking for them, the computer needs a way for the script to refer to the particular spots in the computer's memory where the various values are stored. We give each memory location a specific name in order to be able to refer to its contents without having to know where in memory the computer has put it. As the values we need to store will be different depending on what calculation we are doing these named memory locations are called 'variables'.

If we create a variable called width and put 1024 into that variable in our script, the next time that we reference width, we get the 1024 back and that will be used in the calculation or other process that use the variable until such time as we change the value. If the next time that we run the script we store 1280 in width, the script will use 1280 in the calculations instead of 1024.

Another way of looking at this is to consider what happens when you visit a fancy restaurant on a cold night. The restaurant may have a cloakroom with an attendant where you can leave your coat. The cloakroom attendant will provide you with a claim ticket for you to use when you are ready to leave and want your coat back. This ticket will have a number on it that allows the cloakroom attendant to find your coat. JavaScript variable names are the computer equivalent of the ticket number and the value contained within the variable is the computer equivalent of your coat.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow