What are Variables?
In order to understand how a variable affects a computer program, it's first necessary to understand what one is. A computer program can be viewed as a list of things the computer must do to perform a certain task. For example, a pseudocode program for checking email and playing a sound when new mail arrives might look something like the following.
1: connect "mail.isp.com", "email" 2: say "Do I have any mail?" 3: if new_mail then play "New mail sound"
Each step in the program must remember what the previous steps did. Without this, the say function in the pseudocode wouldn't know who to talk to and new_mail wouldn't know whether or not there was new mail. Let's look at a more realistic piece of pseudocode, during which each step will store what happened in that step in a variable.
1: socket = connect "mail.isp.com", "email" 2: new_mail = socket.say "Do I have any mail?" 3: if new_mail then play "New mail sound"
Ways to Think of Variables
Think of a variable as a box. Code places information it will need later into that box, or variable. It's like storing away winter clothes during the spring. You know you're going to want those clothes again next winter so you stick them in the box until they're needed.
In Step 1 of the pseudocode, the connect function stores its network connection with the email server in a variable called socket. This is signified by the use of the = character, known as the assignment operator. This step assigns the information generated by the connect function to the socket variable. When a function generates information to be assigned to a variable, it is said to "return" that information.
A variable can also be thought of as a device. The connect function returned a device, in this case an intercom through which you can talk to the email server. Step 2 performs an action with this device; it will say something to the server with the socket variable.
Since performing an action on a variable is done with the "dot syntax," saying something to the server through the socket variable is stated as socket.say. Step 2 will take the information returned by the socket.say function (in this case, whether there is any new mail) and store it in the new_mail variable. The final line of the pseudocode plays a sound if there is new mail.