Skip to content

Instantly share code, notes, and snippets.

@CodeDraken
Last active January 20, 2020 22:46
Show Gist options
  • Select an option

  • Save CodeDraken/5488cc827308d6597ea38b081d482b95 to your computer and use it in GitHub Desktop.

Select an option

Save CodeDraken/5488cc827308d6597ea38b081d482b95 to your computer and use it in GitHub Desktop.
Demonstrating a closure
// 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
@indorock
Copy link

// 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.

@CodeDraken
Copy link
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