The use of variables are key to all programming languages. You may remember the x’s and y’s from your high school algebra class. In programming, variables have even more meaning than just some vague idea of an unknown value. In programming, a variable is used as the name of a particular information storage area. You can then use that variable name to call whatever you happened to store there. If you throw away the old stuff and put something new in the storage are, the variable calls the new stuff.
However, there are still some things you will need to learn about data types because there are some side effects to not telling what type of information you want to store.
In any case, the information still has a variable name. Here is an exercise that
1) gathers information from a prompt box,
2) puts it into a variable,
3) does a calculation, and
4) sends the answer back in an alert.
Add this code to the of a new web page
var SquareThis = prompt(“Enter a number you would like to square.”);
Answer = SquareThis * SquareThis;
Basic Programming Skills in this Bit of Code
1. When you do any kind of programming, you have to think of what pieces of information the computer will need to identify and hold on to. Then you make variables to hold the information. In this example, we need to hold two pieces of information, 1) the number that will be squared, 2) the answer.
4. Notice that the function prompt requires an argument just like the alert() did. Notice too that the argument is in ” “, which means that the argument is a String data type.
5. Now the script needs a variable to hold the answer. This is done with “var Answer;”
6. Everything is in place now to do the math: “Answer = SquareThis * SquareThis;” The part that tells the computer what kind of math to do is called an operator. The main operators are +, -, *, / (add, subtract, multiply, divide). There are many other operators, as well. A square is any number multiplied by itself; so this formula multiplies SquareThis by SquareThis.
7. The program has an answer, but it needs to tell the user. Again, we will use an alert box.
8.Now change the formula to do something else. Try adding another variable and another alert() to ask for another number (or several.) Here are some operators for you to experiment with:
+ Adds two numbers
– Subtracts two numbers
/ Divides two numbers
++ Adds one to a number (only needs one variable)
— Subracts one from a number (only needs one variable)