Search code examples
javascriptpythonfunctioncountercycle

Why doesn't this cycling function in javaScript return 0 every time? How would I do something similar in python?


I'm new to programming and am learning a bit of javaScript after knowing a bit of Python. I'm using javaScript to control elements inside a mobile AR app and I created a very simple cycler function that works exactly as I want it to but honestly I'm trying to understand WHY it works! I wanted a function that would cycle 1,2,3 on each tap. First tap would return '1', second tap '2', third tap '3', then repeat this sequence on additional taps. Here is what I came up with after lots of trial, error and googling:

const cycler = {
	    current: -1,
	    cycle: function() {
		    if (cycler.current == 3) {
			    cycler.current = 0;
		    } else {
			    cycler.current++;
		    }
		    console.log(cycler.current);
	    }
}

cycler.cycle()
cycler.cycle()
cycler.cycle()
cycler.cycle()
cycler.cycle()

On the tap event, I call cycler.cycle(); and it works...returning 1,2,3,1,2,3,etc. corresponding to my taps...but I don't understand why it doesn't just return 0 every time I tap. Why isn't 'current' being reset to '-1' every time I call this? How would I do something similar in python? How do I think about this? Thanks for any insight!


Solution

  • Your cycler is an object literal in javascript. It has a property, current, and a method, cycle. Calling the method does not re-create the object, it just runs the function.
    As you know, the function simply increments the value of the current property (unless the current value is 3, of course, in which case it resets the value to 0.)

    In python you might make a class that creates a counter object. Its constructor would contain code very similar to the object you created here.
    If you keep making new instances from that class and call .cycle once on each instance, your log will contain a bunch of 0s as you were expecting.
    However, if you call .cycle on the same instance repeatedly, you'll get the behavior you found here.