JavaScript Functions - Exercise 3
A closure keeps access to variables from its outer function even after that function returns.
function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
console.log(counter(), counter()); // 1 2Recursion is a technique in which a function calls itself with a smaller or simpler input. It must include a base case that returns without another recursive call, as the factorial example demonstrates.
function factorial(number) {
if (number <= 1) return 1;
return number * factorial(number - 1);
}
console.log(factorial(4)); // 24bind creates a new function with a permanently selected receiver for ordinary function calls.
function introduce() {
return `I am ${this.name}`;
}
const person = { name: "Ada" };
const introduceAda = introduce.bind(person);
console.log(introduceAda()); // I am AdaArrow functions capture this lexically from the surrounding scope instead of creating a new receiver.
const user = {
name: "Ada",
showLater() {
setTimeout(() => console.log(this.name), 0);
}
};
user.showLater();Composition combines small functions so the output of one becomes the input of another.
const double = (value) => value * 2;
const addOne = (value) => value + 1;
const result = addOne(double(4));
console.log(result); // 9A generator returns an iterator and pauses at each yield until next() is called.
function* steps() {
yield "first";
yield "second";
}
const iterator = steps();
console.log(iterator.next().value); // firstMemoization caches results so repeated calls with the same input can avoid repeated work.
const cache = new Map();
function square(number) {
if (!cache.has(number)) cache.set(number, number * number);
return cache.get(number);
}
console.log(square(6)); // 36Without a base case, recursive calls continue until the call stack overflows.
function countdown(number) {
if (number === 0) return;
console.log(number);
countdown(number - 1);
}
countdown(3);Use bind() to create a function whose this value is fixed for later calls.
const user = { name: 'Ada' };
function greet() { return `Hello, ${this.name}`; }
const greetUser = greet.bind(user);
console.log(greetUser());A function factory returns a new specialized function based on the configuration it receives.
function createValidator(minimum) {
return value => value.length >= minimum;
}
const isLongEnough = createValidator(8);
console.log(isLongEnough('JavaScript'));