Count remainder in JQuery Text

Hi there, this the code →

I have difficulty understanding the causality of programming events in this part:

  $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);

Hi there codeispoetry,

does this help…

   wordsArray.length = 3

   count ++

   % is the modulus operator

   count = 0, count%3 = 0
   count = 1, count%3 = 1
   count = 2, count%3 = 2
   count = 3, count%3 = 0
   count = 4, count%3 = 1
   count = 5, count%3 = 2
   count = 6, count%3 = 0

   etc, etc

coothead

1 Like

Yes sir, Thanks.
So it is the remainder that is finally counted. Right?

If yes then please help me further how the whole causation is working:

  $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);

I think I got it. Repetition here:

0
1
2
0
1
2
0
1
2

Repetition giving array position in an infinite scheme.

Hi there codeispoetry,

that is correct. :winky:

Further reading:-

MDN - Remainder ( % )

coothead

1 Like

Thanks. Very concise and crisp explanation. Thank you so much.

 
 
    No problem, you’re very welcome. :winky:

coothead

1 Like

Sir, can we also accomplish it through vanilla JS?

Yes, you may. :winky:

Here is an example…

https://codepen.io/coothead/pen/yLNrwGK

You will notice that the CSS is removed from the script.

coothead

2 Likes

In JQuery(Javascript) array is not defined from “0”?
But 1,2,3,4,5… onwards?

Precisely,
In

wordsArray = ["Beta", "Gamma", "Delta", "Alpha"];

wordsArray[0] is Beta or wordsArray[1] is Beta?

What causes you to think that it starts at 1?

In JavaScript as with most other languages, it starts at zero.

1 Like

I got it now. My previous understanding was a slight deviation →

It is actually:
1
2
3
0

1
2
3
0

So wordArrays[0] also comes in the infinite loop.