StrugglingCoder StrugglingCoder - 4 months ago 16
HTML Question

why is JavaScript Closure returning undefined

I know something very basic I am missing . But can't find what's wrong with it ?

<!DOCTYPE html>
<html>
<body>

<p>A function can access variables defined inside the function:</p>

<button type="button" onclick="alert(makeMyCounter.increment)">Click Me!</button>

<p id="demo"></p>

<script>
var makeMyCounter = function () {
var privateCounter = 0;


return {
increment : function() {
privateCounter += 1;
},
decrement : function() {
privateCounter += -1;
}
}
}();


</script>

</body>


Why is privateCounter returning undefined ? But when debugged via browser , it is being assigned 1 though .

Answer

You using method as property, to use method should use like that:

makeMyCounter.increment()

next thing You not return in method so it will be undefined. Add return:

return {
        increment : function() {
            return privateCounter += 1;

        },
        decrement : function() {
            return privateCounter += -1;
        }
    }
Comments