JavaScript Cheat Sheet that you should bookmark
In JavaScript, there are three keywords available to declare a variable, and each has its differences. Those are var
, let
and const
.
Variables declared with const
keyword can’t be reassigned, while let
and var
can.
I recommend always declaring your variables with const
by default, but with let
if it is a variable that you need to mutate or reassign later.
Scope | Reassignable | Mutable | Temporal Dead Zone | |
---|---|---|---|---|
const | Block | No | Yes | Yes |
let | Block | Yes | Yes | Yes |
var | Function | Yes | Yes | No |
**const** person **=** "Nick";
person **=** "John" *// Will raise an error, person can't be reassigned*
**let** person **=** "Nick";
person **=** "John";
console.log(person) *// "John", reassignment is allowed with let*
The scope of a variable roughly means “where is this variable available in the code”.
var
declared variables are function scoped, meaning that when a variable is created in a function, everything in that function can access that variable. Besides, a function scoped variable created in a function can’t be accessed outside this function.
I recommend you to picture it as if an X scoped variable meant that this variable was a property of X.
**function** myFunction() {
**var** myVar **=** "Nick";
console.log(myVar); *// "Nick" - myVar is accessible inside the function*
}
console.log(myVar); *// Throws a ReferenceError, myVar is not accessible outside the function.*
Still focusing on the variable scope, here is a more subtle example:
**function** myFunction() {
**var** myVar **=** "Nick";
**if** (**true**) {
**var** myVar **=** "John";
console.log(myVar); *// "John"// actually, myVar being function scoped, we just erased the previous myVar value "Nick" for "John"*
}
console.log(myVar); *// "John" - see how the instructions in the if block affected this value*
}
console.log(myVar); *// Throws a ReferenceError, myVar is not accessible outside the function.*
Besides, var declared variables are moved to the top of the scope at execution. This is what we call var hoisting.