Skip to content

Commit

Permalink
Learned about 5 types of Scopes: Global, function, block, module and …
Browse files Browse the repository at this point in the history
…lexical
  • Loading branch information
sohail019 committed Jul 31, 2024
1 parent 4a12dcf commit ce4a683
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// 1. Global Scope

let globalVar = 'I am Global'

function checkGlobalScope(){
console.log(globalVar); // Accessible here
}

checkGlobalScope()
console.log(globalVar); // Accessible here too


// 2. Function Scope

function checkFunctionScope(){
let functionVar = "I am Function Variable";
console.log(functionVar); // Accessible here
}

checkFunctionScope();
// console.log(functionVar) // Error: functionVar is not defined


// 3. Block Scope

if(true){
let blockVar = 'I am Blocked Variable'
console.log(blockVar); // Accesible here
}

// console.log(blockVar); // Error: blockVar is not defined

// 4. Module Scope
// const myModule = require('./myModule.js')
// console.log(myModule); // Works because it's imported

// Lexical Scope

function outer(){
const outerVar = "I am Outer"

function inner(){
console.log(outerVar); // Accesible here due to lexical scoping
}
inner()
}

outer()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const moduleVar = "I am Module-Scoped"

export default moduleVar;

0 comments on commit ce4a683

Please sign in to comment.