Estoy leyendo el excelente libro de Marijn Haverbeke, "Eloquent JavaScript". https://eloquentjavascript.net/
No entiendo este ejemplo de cierres donde el number no está definido, pero no hay error.
¿Es number una función o un parámetro?
No hay nada que indique que el number se pasa como parámetro la segunda vez.
function multiplier(factor) { return number => number * factor; } let twice = multiplier(2); console.log(twice(5)); // → 10Comprender cómo funcionan los cierres es bastante difícil, pero cuando el ejemplo que está viendo mezcla arbitrariamente una declaración de función con una función de flecha , como lo hace esta, si no comprende cómo funcionan las funciones de flecha, hace que sea más difícil de entender.
Aquí hay un ejemplo un poco más fácil que no usa una función de flecha para mostrar lo que está pasando.
// `multipler` takes a factor as an argument function multiplier(factor) { // It returns a function that - when it's called - // accepts a number return function (number) { // And the return from that function // is the factor * number return number * factor; } } // So we call `multipler` with a factor and assign the // function it returns to our `twice` variable let twice = multiplier(2); // We can then call the function assigned // to `twice` with a number, and the resulting // return from that function will be factor * number console.log(twice(5));En términos del ejemplo que usa esa función de flecha:
// We pass in a factor to the `multipler` function multiplier(factor) { // We return a function that accepts a number // and returns factor * number // (I've added parentheses around the number // parameter to clearly show it) return (number) => number * factor; } // So we call `multipler` with a factor and assign the // function it returns to our `twice` variable let twice = multiplier(2); // We can then call the function assigned // to `twice` with a number, and the resulting // return from that function will be factor * number console.log(twice(5));