diff --git a/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/08_closure_with_asynchronous.js b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/08_closure_with_asynchronous.js new file mode 100644 index 0000000..2a5e4b6 --- /dev/null +++ b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/08_closure_with_asynchronous.js @@ -0,0 +1,23 @@ +// Closure with Asynchronous Code + +function fetchData(url){ + + fetch(url) + .then(response => { + if (!response.ok) { + throw new Error(`Network response was not ok`) + } + return response.json() + }) + .then(data => { + console.log(data); + }) + .catch(error => { + console.log( + "There has been a problem with your fetch operation:", + error + ); + }) +} + +fetchData("https://api.github.com/users/sohail019"); \ No newline at end of file diff --git a/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/09_partial_applications_and_currying.js b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/09_partial_applications_and_currying.js new file mode 100644 index 0000000..53c12b8 --- /dev/null +++ b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/09_partial_applications_and_currying.js @@ -0,0 +1,16 @@ +// Partial applications and currying + +function multiply(x){ + return function(y){ + return x * y + } +} + + +const double = multiply(2) +console.log(double(5)) // 10 + +const triple = multiply(3) +console.log(triple(5)) // 15 + +// Here, multiply is curried function that returns a closure, allowing for partial application of the multiple operation. \ No newline at end of file diff --git a/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/10_preserving_states.js b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/10_preserving_states.js new file mode 100644 index 0000000..d6ae4cb --- /dev/null +++ b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/10_preserving_states.js @@ -0,0 +1,20 @@ +// Preserving States + +function makeToggle(){ + let isOn = false + + return function(){ + + isOn = !isOn + return isOn + } +} + +const toggle = makeToggle(); + +console.log(toggle()) // true +console.log(toggle()) // false +console.log(toggle()) // true + +// The makeToggle function creates a closure that preserves the isOn state across multiple calls, effectively toggling the state each time it is invoked. +