Variables are representative names in a program. Just as x may stand for some as-yet-unknown value in algebra, or x may mark the spot where the treasure is buried on a pirate’s map, variables are used in programming to represent something else.
You can think about variables as containers that contain data. You can give these containers names, and later you can recall and change the data in a variable by using its name.
Without variables, every computer program would have only one purpose. For example, the following one-line program doesn’t use variables:
alert(3 + 7);
Its purpose is to add together the numbers 3 and 7 and to print out the result in a browser popup window.
The program isn’t of much use, however (unless you happen to need to recall the sum of 3 and 7 on a regular basis). With variables, you can make a general purpose program that can add together any two numbers and print out the result, like the following example:
var firstNumber = 3;
var secondNumber = 7;
var total = Number(firstNumber) + Number(secondNumber);
alert (total);
Taken a step further, you can expand this program to ask the user for two numbers and then add them together, like the following example:
var firstNumber = prompt("Enter the first number");
var secondNumber = prompt("Enter the second number");
var total = Number(firstNumber) + Number(secondNumber);
alert (total);
No comments:
Post a Comment