Scope > Introduction
Scope > Global scope
// Variable in global scope
let globalVariable = 'Hello';
console.log(globalVariable);
function functionName() {
// The variable is accessible since the variable is in the global scope
console.log(globalVariable);
}
functionName();
// Output: Hello
Scope > Global scope > code example
Scope > Local scope
// Global scope
let firstName = 'John';
function firstFunction() {
// Local scope
let lastName = 'Doe';
console.log(firstName + '' + lastName);
}
function secondFunction() {
let greeting = 'Hi there!';
return greeting;
console.log(greeting);
}
firstFunction();
secondFunction();
Scope > Local scope > code example
Scope > Lexical scope
function outerFunction(){
if(true) {
// x is accessible everywhere inside outerFunction() but not outside
let x = 'Hi';
console.log(y); // y is not accessible, returns a ReferenceError
}
function nestedFunction(){
if(true) {
// y is accessible everywhere inside nestedFunction but not outside
let y = 'Hello';
console.log(x); // x is accessible, output: Hi
}
if(true) {
console.log(y); // y is accessible, output: Hello
}
return nestedFunction;
}
}
outerFunction();
Scope > Lexical scope > code example
Scope > Closures
function person(firstName, lastName){
let age = 19;
// Inner function has access to the outer function
function completePerson() {
return firstName + ' ' + lastName + ' is ' + age;
}
return completePerson();
}
person('John', 'Doe');
// Output: John Doe is 19
Scope > Closures > code example
function outerFunction(){
let greeting = 'Hi';
let counter = 1;
function innerFunction(){
if(counter === 1) {
console.log(greeting);
} else {
console.log('Not equal to 1 anymore');
}
counter++;
}
return innerFunction;
}
let example = outerFunction();
example();
example();
Scope > Closures > code example 2
function counter() {
let a = 2;
let b = function() {
a++;
return a;
};
return b;
}
let c = counter();
console.log(c() + ' , ' + c());
Scope > Closures > code example 3
Scope > Block scope
// Block scope inside if statement
if (10 == '10') {
// statement here
}
// Block scope for the for loop
for (let i = 0; i < 20; i++) {
// code block here
}
// An empty object literal
var a = {}
// Undefined object
{ var a }
Scope > Block scope > code example
// A new block scope is created between the curly braces
if (true) {
var foo = 'Foo';
let bar = 'Bar';
}
console.log(foo); // Output: Foo
console.log(bar); // Output: ReferenceError: bar is not defined
Scope > Block scope > code example 2