Last active
January 20, 2020 22:46
-
-
Save CodeDraken/5488cc827308d6597ea38b081d482b95 to your computer and use it in GitHub Desktop.
Demonstrating a closure
This file contains hidden or 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
| // Closure Example | |
| function exponent (x) { | |
| // returns a new function to be called later | |
| // this function remembers the x argument | |
| return function (y) { | |
| // ** is the exponentiation operator | |
| // same thing as Math.pow() or y to the power of x | |
| return y ** x | |
| } | |
| } | |
| // creates a function that squares a number | |
| // it *remembers* that x is 2 | |
| // or in other words, it still has access to the | |
| // lexical environment that it was created in | |
| const square = exponent(2) | |
| console.log(square(2), square(3)) // 4, 9 | |
| // cubed | |
| console.log(exponent(3)(2)) // 8 |
Author
// same thing as Math.pow() or x to the power of y
Should say
y to the power of x
Innocuous mixup but it did confuse me for a good 5 minutes as I was reading the example.
Thanks, updated it
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should say
y to the power of xInnocuous mixup but it did confuse me for a good 5 minutes as I was reading the example.