Most of what we’ve talked about so far: numbers, booleans, strings have been different kinds of values.
But we’ve seen variables in the expression exercises and the drawing and animation environments.
Must start with a letter or _
.
Most consist of just letters, numbers and _
.
(This is slightly simplified but good enough for now.)
i
enoughSleep
width
height
drawFrame
Make multi-word names by smooshing together the words and capitalizing the first letter of all but the first word. This is called camelCase.
'width'
vs width
The former is string whose value is the text “width”.
The latter is a variable whose name is “width”.
if
, true
, false
, for
, while
, return
, and some others.
You can’t use them as variables names.
We assign values to variables with =
width = 800
When we include a variable in an expression it evaluates to whatever value it has been assigned.
width
⟹ 800
width / 2
⟹ 400
const x = 42;
The value of x
will never change.
const
stands for “constant”.
Knowing that a value will never change makes it much easier to understand your code.
Use const
whenever you can.
let y = 123;
y
can be assigned a different value later.
let
is just how mathematicians talk.
📜 For history buffs only. 📜
var year = 2014;
Old-fashioned.
Mostly like let
but with some unfortunate wrinkles.
Don’t use it.
But you may see it in other people’s code.
… your name is like a variable.
You exist independent of your name.
You might have different names in different contexts.
A single name might refer to different people at different times.
“First violin” is the name for a particular person in an orchestra.
But the name will refer to different people over time.
You have to “dereference” it, i.e. figure out who it’s referring to.
“Please give this rosin to the first violin.”
Who’s the first violin? Oh, her.
When you write code you are communicating to human readers about what the program does.
Choosing good names is one of the main ways you can make this communication clear.
I don’t care if you use bad words as your variables names. (Though some people might.)
But I do care if you use words that don’t express your meaning.
const poop = 32;
What does this mean? Seems like it’s just being used as a meaningless word.
Anyone reading this code has to figure out what it really means and then mentally translate every time they see it.
Programming is hard enough; don’t make it harder.