Created
October 4, 2019 22:55
-
-
Save erkanzileli/54b08e0a0cb30341f5da95b126a501c1 to your computer and use it in GitHub Desktop.
Closure vs. High Order Functions in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A closure does not mean that it necessarily is returned by a function. | |
// A closure generally is a function that has access to the declaration context's scope. | |
// A closure example without returning a function | |
var oddNumber = 3; | |
function isOddNumberIsReallyOdd() { | |
return oddNumber % 2 === 1; | |
} | |
console.log(isOddNumberIsReallyOdd(oddNumber)); | |
// Output: true | |
// A closure example with returning a function | |
function getWordRepeater(n) { | |
// return a word that repeated "n" times | |
return function(word) { | |
let result = ""; | |
for (let i = 0; i < n; i++) { | |
result += word; | |
} | |
return result; | |
}; | |
} | |
var wordRepeater = getWordRepeater(3); | |
console.log(wordRepeater("hi")); | |
// Output: hihihi | |
// A high order function does mean that it returns a function | |
function getOddDetector() { | |
return n => n % 2 === 1; | |
} | |
var oddDetector = getOddDetector(); | |
console.log(oddDetector(4)); | |
// Output: false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment