Variables

Variables are names for values

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.

Syntax of names in Javascript

Must start with a letter or _.

Must consist of just letters, numbers and _.

(This is slightly simplified but good enough for now.)

Examples

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.

A few words that look like legal names are reserved

if, true, false, for, while, return, and some others.

You can’t use them as variables names.

Variables hold values

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

Two ways to define variables

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.

A third way to define variables

📜 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.

A way to think about the relationship between values and variables

If you are a value …

… your name is like a variable.

You exist independent of your name.

You might have different names in different contexts.

On the other hand

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.

When someone uses a name

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.

Some notes about style

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.