Scope
What is Scope?
Scope determines the accessiblity (visibility) of variables and other resources in areas of your code.
Why is it used?
-
Provides security to your code
-
Improves efficiency
-
Tracks and reduces bugs
-
Solves naming collisions with variables of the same name
Scope in Javascript
-
Global Scope
-
Local Scope
Global Scope
A variable that is written outside of a function
Global Scope
//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
Local Scope
A variable that is written inside of a function
Local Scope
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
What is accessible?
var menu = 'spinach';
function secretMenu(){
var special = 'cheeseburger';
function staffMenu(){
var verySpecial = 'orange chicken';
}
}
- global scope
- secretMenu()
- staffMenu()
Block Statements
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
}
Block 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'
Block Scope (cont)
ECMAScript* 6 introduced two new keywords to provide block scope variables (and constants)
- let
- const
*ECMAScript is a trademarked scripting-language specification standardized by Ecma International. It was created to standardize JavaScript
let
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'
const
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
Scope
By vic_lee
Scope
- 330