Skip to content

Instantly share code, notes, and snippets.

@erkanzileli
Created October 4, 2019 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkanzileli/54b08e0a0cb30341f5da95b126a501c1 to your computer and use it in GitHub Desktop.
Save erkanzileli/54b08e0a0cb30341f5da95b126a501c1 to your computer and use it in GitHub Desktop.
Closure vs. High Order Functions in JavaScript
// 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