Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Javascript, local variables are parameters?

Tags:

javascript

I was reading the book when I saw this

function multiplier(factor) {
  return number => number * factor;
}
  1. I know that closures are functions within functions that access the parent function's local variables but is a returned function still considered a closure?
  2. If this is considered a closure, that means that parameters are also considered local variables. Is this true? If so, is this true in every programming language? I've seen some posts saying that they're not exactly the same. What are the differences?
like image 911
jozen Avatar asked Jan 26 '23 11:01

jozen


1 Answers

  1. While it's true that this is an example of a closure , this is also an example of a curried function.

  2. Yes, the function with its parameters and local variables are added to the call stack and that's true in (most?) programming languages. I don't know of any language where that isn't true, but one could be written otherwise so I'm sure someone's done it. I would say the major difference between parameters/arguments and local variables is that the function has control over the local variables whereas the parameters are controlled by whatever is calling it. You can see the difference here, but they are more or less the same.

// You'll need to actually look in your dev tools to see the result

const test = test => test2 => test2;
console.log("Test:");
console.dir(test);
console.dir(test());
const best = function(best) {
    return function(best2) {
        return best2;
    }
}
console.log("Best:");
console.dir(best);
console.dir(best());

// You'll need to actually look in your dev tools to see the result
like image 97
Jonathan Rys Avatar answered Jan 29 '23 14:01

Jonathan Rys