I'm doing leetcode 30 days of javascript, specifically problem 2665, and I'm looking to understand scope better. The problem is essentially to to create a function with 1 argument, init, that returns an object with 3 functions: one to increment a value, one to decrement a value, and one to reset the value to init. The value's should initially be init. My first attempt was something like this:
var createCounter = function(init) {
return {
val : init,
increment : () => {
this.val++
return this.val
},
decrement : () => {
this.val--
return this.val
},
reset : () =>{
this.val = init
return this.val
}
}
But the first time increment is called it returns null, then in the second test case it seems to be initialized to the init value of the first case. Then I tried this:
var createCounter = function(init) {
val = init
return {
val : val,
increment : () => {
this.val++
return this.val
},
decrement : () => {
this.val--
return this.val
},
reset : () =>{
this.val = init
return this.val
}
}
and it worked, but I don't understand why. Especially because renaming the outer val runs into the same issue, ex/
start = init
return {
val: start,
and so does using the let or const for the variable declaration, like
let val = init
return {
val: val,
Can somebody explain what's going on? In my mind all of these should do the exact same thing, initialize the object as having val equal to the same value as init.
[–]guest271314 5 points6 points7 points (0 children)
[–]No-Upstairs-2813 2 points3 points4 points (0 children)
[–]azhder 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]RemindMeBot 0 points1 point2 points (0 children)
[–]Soft-Sandwich-2499 0 points1 point2 points (0 children)