Javascript Closure Not Taking Inputs Consistently
I have two javascript closures and I'm trying to understand why one will accept and input with a particular syntax and the other will reject. function multiply(factor) { var ace
Solution 1:
The difference is whether you are creating the closure right away through an IIFE, or a function that makes the closure when called.
Your first snippet written in the second style would be
var yup = (functionmultiply(factor) {
returnfunctionace(number) {
return number*factor;
};
})(4); // the multiply(4) call is inlined into the statement with the definitionconsole.log(yup(5));
Your second snippet written in the first style would be
functionmakeAdd(k) {
console.log(k);
var counter = k;
returnfunction (j) {
counter += 1;
return counter*j;
}
}
var add = makeAdd(3);
add();
console.log(add(5));
Post a Comment for "Javascript Closure Not Taking Inputs Consistently"