Provides security to your code
Improves efficiency
Tracks and reduces bugs
Solves naming collisions with variables of the same name
//global scope
var greeting = 'Aloha';
console.log(greeting); // log 'Aloha'
function welcome(){
console.log(greeting); //greeting is accessible here and everywhere else
}
welcome();
Lives as long as your application lives
function sayHi(){
var greet = 'hi'; // can only be accessed within the function
return greet;
}
sayHi();
Lives as long as your functions are called and executed
var menu = 'spinach';
function secretMenu(){
var special = 'cheeseburger';
function staffMenu(){
var verySpecial = 'orange chicken';
}
}
Block statements (i.e. if statements, for, while loops, etc.) don't create a new scope. Variables defined inside of a block statement will remain in the scope they were already in.
if(true){
var menu = 'spinach'; //still in global scope
}
Redeclaring a variable inside a block statement will also redeclare the variable outside the block
var menu = 'spinach';
console.log(menu); // logs 'spinach'
if(true){
var menu = 'bacon cheeseburger';
console.log(menu); // logs 'bacon cheeseburger'
}
console.log(menu); // logs 'bacon cheeseburger'
ECMAScript* 6 introduced two new keywords to provide block scope variables (and constants)
*ECMAScript is a trademarked scripting-language specification standardized by Ecma International. It was created to standardize JavaScript
Redeclaring a variable using let will not change the variable that is outside the block
var menu = 'spinach';
if(true){
let menu = 'bacon cheeseburger';
console.log(menu) // logs 'bacon cheeseburger'
}
console.log(menu) // logs 'spinach' global var doesn't change
var i = 'apple';
for(let i = 0; i<10; i++){
console.log(i); //logs 0 - 9
//let i is visible only within the for loop
}
console.log(i); // logs 'apple'
Similar to let variables but const cannot be reassigned
const menu = 'mac and cheese';
console.log(menu); //logs 'mac and cheese'
menu = 'kale';
console.log(menu); // error
You can change the properties of a constant object or elements of a constant array. But you cannot reassign them.
const restaurant = {
name: 'Panda Express',
item: 'orange chicken'
}
restaurant.rating = 5;
console.log(restaurant); // logs restaurant object
restaurant = {
name: 'Zippys',
item: 'chilli'
}
console.log(restaurant) // error