=
let color = "blue"
let fruit = "berry"
color + fruit // "blueberry"
fruit.toUpperCase() // "BERRY"
let
declares a variable in JavaScriptconst
declares a variable that cannot be reassignedvar
is like let
but is no longer recommendedYou can only use let
once per variable name, per scope
let name = 'Grace';
let name = 'Hopper';
// Identifier 'name' has already been declared
Think of memory as a giant warehouse. Computer memory is vast and filled with boxes of various sizes.
If memory is a giant warehouse...
Which is clearer?
60 * 60 * 24
let secondsPerMinute = 60;
let minutesPerHour = 60;
let hoursPerDay = 24;
let secondsPerDay = secondsPerMinute * minutesPerHour * hoursPerDay;
Let's spend a few minutes just playing around with variables in the JavaScript console.
Some things to try:
let snack = "Apple"
Think of a variable as an arrow pointing to a value.
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'
let fruit = "Apple"
let 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.
Most messages return new values:
let fruit = "banana"
let snack = fruit.toUpperCase()
"banana"
and "BANANA"
are two different values in memory. The original value is still sitting around and still pointed to by fruit
.
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.
const
is just like let
, but also prevents reassignment
const
is constant after it's been set onceconst pi = 3.14159;
pi = 7;
TypeError: Assignment to constant variable.
While
const
prevents reassignment, it does not prevent changing the properties within objects
/