var vs let vs const
ES2015 (or ES6) introduced two new ways to create variables, let and const.
var​
- var is function scoped
- This will give undefined when accessing a variable before it's declared
- it creates a global property on window with the same name.
- is reassignable.
- is redeclarable.
Ex: var <<variable_name>>;
Example:
--------
var city = "Coral Springs";
console.log(window.city);
Example2:
--------
var city = "Florence";
function bubble() {
var city = "Siena";
console.log(city);
}
bubble(); // "Siena"
console.log(city); // "Florence"
let​
- let is block scoped.
- ReferenceError when accessing a variable before it's declared
- it does not create any global property on window.
- is reassignable.
- is not redeclarable.
Ex: let <<variable_name>>;
What that means is that a variable created with the let keyword is available inside the “block” that it was created in as well as any nested blocks. When I say “block”, I mean anything surrounded by a curly brace like in a for loop or an if statement.
const​
const is almost exactly the same as let. However, the only difference is that once you’ve assigned a value to a variable using const, you can’t reassign it to a new value.
- block scoped
- ReferenceError when accessing a variable before it's declared
- it does not create any global property on window.
- is not reassignable.
- is not redeclarable.
Ex: const handle = 'test';
tip
The take away above is that variables declared with let can be re-assigned, but variables declared with const can’t be.