Skip to content

Commit

Permalink
Learned about Closures, how to encapsulate data, Multiple closures an…
Browse files Browse the repository at this point in the history
…d Loops in closures
  • Loading branch information
sohail019 committed Jul 31, 2024
1 parent 4f6ba03 commit 359e07b
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Closures

// Simple Closure

function outerFunction(){
const outerVar = "I am Outside!"

function innerFunction(){

console.log(outerVar);
}

return innerFunction;
}

const closureFunction = outerFunction()
closureFunction(); // I am outside

// In this example, innerFunction is a closure.
// It captures variable outerVar from it's lexical scope and retains access to it even after outerFunction has finished executing.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Data Encapsulation with Closures

function createCounter(){

let count = 0;

return function(){
count += 1
return count
}
}

const counter = createCounter()
console.log(counter()) // 1
console.log(counter()) // 1
console.log(counter()) // 3

// In this example, 'count' is encapsulated within the function returned by createCounter, allowing it to maintain state between calls.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Multiple Closures

function createAdder(x){
return function(y){
return x + y
}
}

const addFive = createAdder(5)

const addTen = createAdder(10)

console.log(addFive(2)) // Output: 7

console.log(addTen(7)) // Output: 17


function fullName(firstName){
return function(lastName){
return `${firstName} ${lastName}`
}
}

const myName = fullName('Sohail')

console.log(myName("Shaikh")); // Sohail Shaikh
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Closure in Loops

// Incorrect behavior
var funcs = []
for(var i = 0; i < 3; i++){
funcs[i] = function(){
console.log(i);
}
}

funcs[0]() // 3
funcs[1]() // 3
funcs[2]() // 3


// Corrected with let

for(let i = 0; i < 3; i++){
funcs[i] = function(){
console.log(i);
}
}

funcs[0]() // 0
funcs[1]() // 1
funcs[2]() // 2

0 comments on commit 359e07b

Please sign in to comment.