[Reminder-1] var, let, const
florent giraud
Posted on May 9, 2020
I am writing this article at first for me :). Why ?
Just to have a fast reminder about them. But i hope it can help you too !
We will speak about some javascript concepts here:
- scope
- block
We can use let and const since es2015 (or es6). I am assuming you know what is"use strict"
. It will force you to init the variable before using it. In older browser it will work and you will have some weird issues.
SCOPE
The scope is the portion of code where the variable is visible.
In Javascript only function create new scope (arrow function too). That mean if you try:
function() {
var hi = "hello"
}
console.log(hi) // will be undefined
- If a global variable as the same name. The variable inside the function will shadow the global variable (shadowing)
- If variable is declared after it is called. If he is after the called function it will be found because JS use the hoisting that put all variables on the top of the file (Always declare you variable properly).
BLOCK
- A block is what is identified by a pair of curly braces. But except for function it doesn't create a new scope.
that mean's:
if (true) {
var hi = "hello"
}
console.log(hi) // will be "hello" remember hoisting
LET
- With 'let' now you have a scoped version variable even in block
Remember:
if (true) {
let hi = "hello"
}
console.log(hi) // will throw error hi not defined
- "let" doesn't create a global variable.
CONST
It can be scope in a block (remember the if) so it will not be available outside.
const could not be changed or reassigned. Just if the const variable is an object it can be mutate. You can block this behavior by wrapping your object with Object.freeze({})
. Remember here that freeze will just freeze the level first of your object not the nested ones.
And that's it. See you in the next reminder.
Posted on May 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.