Javascript closure and scope riddle -
i'v heard question, , i'm unsure how solve it.
the requirement is: implement function from
preform on following scenario:
var x = from(3); console.log(x()); //outputs 3 console.log(x()); //outputs 4 //todo: implement from()
i tried like:
function from(val) { var counter = val; return function(){ return counter+=1; } }
but first time run it, increments value, that's no go.
var x = from(3); function from(startvalue) { var counter = startvalue; return function() { return counter++; } } console.log(x()); //outputs 3 console.log(x()); //outputs 4
Comments
Post a Comment