|words for functions and variables that we create in our code like
|numbers and words that represent values like
Variables are placeholders in the computers memory that we give a nickname and store some data in.
If we assign a variable called
faceSize the number
50 we can later use it to draw a face and that value will be used.
We can change the value later. That's why it is known as a variable.
Variables are kind of like names for people.
Imagine a story involving three of your friends. It might go something like this: Jerry and Jenny went to the park one day and met their friend Nick.
This story would make sense to you if you know who Jerry, Jenny and Nick are. It wouldn't make as much sense if you didn't know them.
We use names to make it easy to refer to people. I wouldn't have to specify which student I was calling on by using their CUNY id. That would be too hard to memorize. It would also be difficult to call on students based on what seat their sitting in. Third row from the back, 3 seats down is not an easy way to call on someone.
Variables, like names, make it easier to understand what's happening in our code.
50 could be used for anything. But the variable
faceSize is pretty clear in terms of what it should be used for in the sketch.
In the last class we drew a self portrait, using
We can improve this program using variables. Notice I used the same size for the eyes width in my self portrait? I can use one variable to save that value and adjust both eyes at one time:
var eyeSize = 25; ellipse(75, 100, eyeSize); // right eye ellipse(125, 100, eyeSize); // left eye
This improves the program in a couple of ways.
First, it's easier to update. If I want the eyes larger, I change one variable, which is easy to identify, and assign it to a different number.
Second, it's much easier to read. I know that the eyeSize is the third argument in each ellipse function, so I can guess that it's drawing the eyes.
Third, it will make the values easier to change or update, which we will start doing next week.
We can also do this with colors, or string values. My self portrait uses hardcoded values for colors:
"#ffddff". If I want to change the color of any of the parts of the face I need to rewrite this. If I use a variable instead, I can change all of the shapes using each color and change them all at the same time.
If I want to add to the eyes using the same color as the face this will be useful.
Notice I also used
eyeSize / 2 for the size of both pupils. Now they are relative to the size of the eyes. I can update both eyes and pupils by changing one color.
Keep in mind that the string
"plum" has to have quotation marks around it because it is hard data.
faceColor does not have quotation marks because it's a variable.