Variables

Variables are names for values

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.

Syntax of names in Javascript

Must start with a letter or _.

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

🚨 Important 🚨

'width' vs width

The former is string whose value is the text “width”.

The latter is a variable whose name is “width”.

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.

let is just how mathematicians talk.

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.

Naughty words as variable names

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.

For instance

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.

Up next

Functions