

Variables
A variable is a binding between a name and a value. A variable is:
- ▪ declared when a
const
,let
orvar
keyword is used with a name:let myVar
- ▪ initialized when an initial value is assigned to it:
myVar = 1
- ▪ reassigned when its value changes:
myVar = 2
Although you can declare and initialize a variable on the same line of code: let myVar = 1
, the engine will declare and initialize it in 2 different steps.

Primitive vs Object Binding
Imagine you owned a Nintendo console with your favourite game. Only you can play it. You set the high-score and stop playing. Later, you come back to play again. You still hold the high-score.
Your local arcade has the same game. You don't own the arcade machine, you only have the street address of the arcade. You go there, play it and get the high score. A week later, you come back. Your high-score is no longer there. Another player who also had street address of the arcade beat your high-score.
A primitive binding is like owning your own copy of a game. Only you can set the high-score. An object binding is like an arcade machine. You don't own it, you only have the street address. You can set the high-score, but so can others.
JavaScript has 7 types:
- ▪
null
- ▪
undefined
- ▪
boolean
- ▪
string
- ▪
number
- ▪
symbol
- ▪
object
All the types are primitives except for object
.
- ▪ When you assign a primitive to a variable,
let myVar = 1
, the value1
is bound to the namemyVar
. - ▪ When you assign an object to a variable,
let myVar = { a: 1 }
, the value isn't bound tomyVar
. Instead, an object reference is bound tomyVar
. The memory address of{ a: 1 }
.
When assigning or passing variables of a primitive, a copy of the value is created.
index.js
// primitive bindingvar var1 = 1var var2 = var1var var3 = var1var2++console.log(var3)
When assigning or passing variables of an object, a copy of the reference is created. If 2 variables are assigned the same object, changing the value of 1 will change the other.
index.js
// object bindingvar var1 = { a: 1 }var var2 = var1var var3 = var1var2.a++console.log(var3)
When comparing objects using the equality opertor, ===
, the results can be unintuitive. See Referential Equality for details.

Redeclaring
Redeclaring a var
will result in a no-op (nothing will happen on any additional declarations).
Redeclaring a const
or let
results in an error.
index.js
let myVar;let myVar;

undefined vs undeclared
undefined
is the default value of a variable or property.
index.js
let myVar;console.log(myVar);
Attempting to access a variable that hasn't been declared throws a reference error.
Although the error states myVar is not defined
, a more accurate description is myVar is undeclared
.
index.js
myVar
Be aware, the typeof
operator returns "undefined"
for an undeclared variable.
index.js
console.log(typeof myVar)
Feedback
Have any feedback about this note or just want to comment on the state of the economy?