Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. // A closure does not mean that it necessarily is returned by a function.
  2. // A closure generally is a function that has access to the declaration context's scope.
  3.  
  4. // A closure example without returning a function
  5. var oddNumber = 3;
  6.  
  7. function isOddNumberIsReallyOdd() {
  8. return oddNumber % 2 === 1;
  9. }
  10.  
  11. console.log(isOddNumberIsReallyOdd(oddNumber));
  12. // Output: true
  13.  
  14. // A closure example with returning a function
  15. function getWordRepeater(n) {
  16. // return a word that repeated "n" times
  17. return function(word) {
  18. let result = "";
  19. for (let i = 0; i < n; i++) {
  20. result += word;
  21. }
  22. return result;
  23. };
  24. }
  25.  
  26. var wordRepeater = getWordRepeater(3);
  27. console.log(wordRepeater("hi"));
  28. // Output: hihihi
  29.  
  30. // A high order function does mean that it returns a function
  31. function getOddDetector() {
  32. return n => n % 2 === 1;
  33. }
  34.  
  35. var oddDetector = getOddDetector();
  36. console.log(oddDetector(4));
  37. // Output: false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement