Most of what we’ve talked about so far: numbers and booleans 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 _
.
Must 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.
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.
📜 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.