Variables

let color = "blue"
let fruit = "berry"
color + fruit       // "blueberry"
fruit.toUpperCase() // "BERRY"

Let vs Var vs Cont

Rebinding Let

You can only use let once per variable name, per scope

let name = 'Grace';
let name = 'Hopper';
// Identifier 'name' has already been declared

The Warehouse Metaphor

Think of memory as a giant warehouse. Computer memory is vast and filled with boxes of various sizes.

Warehouse from Raiders of the Lost Ark

The Warehouse Metaphor Explained

If memory is a giant warehouse...

Variables as Documentation

Which is clearer?

60 * 60 * 24
let secondsPerMinute = 60;
let minutesPerHour = 60;
let hoursPerDay = 24;
let secondsPerDay = secondsPerMinute * minutesPerHour * hoursPerDay;

Lab: Play In Console

Let's spend a few minutes just playing around with variables in the JavaScript console.

Some things to try:

Variables Point at Values

let snack = "Apple"

snack-apple

Think of a variable as an arrow pointing to a value.

Changing Variables

You can assign and reassign variables at will

let color = "blue" // assign 'blue' to color
let fruit = "berry"// assign 'berry' to fruit
color + fruit      // 'blueberry'

color = "black"    // 'black'
color + fruit      // 'blackberry'

Many Variables One Value

let fruit = "Apple"
let snack = fruit

snack-fruit

After this both snack and fruit are pointing to the same value

This is analogous to placing two labels on the same box.

Return values

Most messages return new values:

let fruit = "banana"
let snack = fruit.toUpperCase()

fruit-banana-snack-banana

"banana" and "BANANA" are two different values in memory. The original value is still sitting around and still pointed to by fruit.

Changing Values

Many messages do not change the data inside the object.

let color = "blue"
color.toUpperCase()     // "BLUE"
color                   // "blue"

This is true for all primitive values.

Constants: Variables that Aren't Variable

const pi = 3.14159;
pi = 7;
TypeError: Assignment to constant variable.

Whileconst prevents reassignment, it does not prevent changing the properties within objects

Summary: Variables

 Previous Next 

Outline

[menu]

/