declaring variables in javascript

ES6 introduced two new ways to declare variables, These along with var, have different qualities especially when it comes to scope. Both Any time that let and const are block scoped, this means they will have the scope of the curly brackets they are found in. Variables declared with var, have function scope, meaning they are available only within the function they are created in. These will be globally scoped if they are not declared in a function.

let
A let variable can be reassigned and updated, but it cannot be declared twice within the same scope. The most popular application for a let variable is within a loop or conditional. This is also helpful when something should run after some amount of time.

let age = 12;
let teen = false;
if(age + 1 >= 13) {
let teen = true
console.log(teen) //true
}
console.log(teen) //false

The first log of teen returns true because it is scoped to the if statement. The second log is scoped to the window.

var
A var variable can be declared twice within the same scope, which would most likely cause confusion and bugs.

var age = 12;
var teen = false;
if(age + 1 >= 13) {
var teen = true
console.log(teen) //true
}
console.log(teen) //true

Logging the teen variable returns true both times because it is not inside of a function.

const
This declaration creates a constant with either local or global scope to the function in which it is declared. The const variables behave similar to let variables, but const variables cannot be updated. It is important to note that a const object is not immutable. That means if the variable declares an object, the properties of the object can change. The object cannot be reassigned.

const me = { name: 'david', age: 13}
me = { name: 'David', age: 31 } //Uncaught TypeError: Assignment to constant variable.
me.name = 'David'
me.age = 31
me.location = 'NYC'
console.log(me) // {name: "David", age: 31, location: 'NYC'}