0

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!

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
jnse
  • 37
  • 1
  • 4
  • 1
    It is printing `0,1,2,3`. can't reproduce problem – Code Maniac Mar 10 '19 at 04:52
  • OP indicated "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!", so printing the desired output is, in fact, "reproducing the problem", so to speak. – Cat Mar 10 '19 at 05:03
  • 1
    Possible duplicate of [JavaScript closures vs. anonymous functions](https://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions) – SherylHohman Mar 10 '19 at 09:02
  • @SherylHohman.... Care to elaborate or help me understand what makes you suspect that this is a duplicate? Elaborating could help me understand new concepts. – jnse Mar 10 '19 at 18:32

2 Answers2

1

When the object gets created in memory it sets the initial current value to -1, and unless the object gets removed, and recreated in memory, the value will be whatever you last set it to.

Tyler Wray
  • 13
  • 3
1

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.

Cat
  • 4,141
  • 2
  • 10
  • 18