Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing using a percentage sign? % JavaScript

When simplifying my code, a stack overflow user changed this line of code:

if (place > sequence.length -1) {
    place = 0;

to this:

 place = place % sequence.length;

and I'm wondering what this line actually does and how you would define the use of this line and the use of the percentage sign. Thanks for help in advance.

like image 681
AntsOfTheSky Avatar asked Feb 25 '17 20:02

AntsOfTheSky


People also ask

How do I use the percent sign in JavaScript?

The % operator is one of the "Arithmetic Operators" in JavaScript, like / , * , + , and - . The % operator returns the remainder of two numbers. It is useful for detecting even/odd numbers (like to make stripes) and for restricting a value to a range (like to wrapping an animated ball around) .

What does percentage symbol mean in JS?

One of them is the percent sign: % . It has a special meaning in JavaScript: it's the remainder operator. It obtains the remainder between two numbers. This is different from languages like Java, where % is the modulo operator.

What does $$ mean in JavaScript?

$ and $$ are valid variable names in JavaScript, they have no special meaning. Usually they set their value to library instances, in your example if you check the closure call, at the end of the file you'll see that $ is jQuery in this case if it is defined and $$ is cytoscape.

What does the percent sign mean in JavaScript?

The JavaScript percent sign doesn’t do modular arithmetic. It’s used for finding the remainder when the first operand is divided by the second operand. This is what JavaScript’s percent sign actually means. For example, if we write: we get 0 since 10 is evenly divisible by 2.

How to compare a string with a number in JavaScript?

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false.

What happens when you compare data of different types in JavaScript?

Comparing data of different types may give unexpected results. When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0.

What are comparison operators in JavaScript?

Like C, C++, Java, Python, and various other languages, JavaScript also supports Comparison operations. Comparison operators are used in logical expressions to determine their equality or differences in variables or values.


1 Answers

(%) is the modulus operator, it will let you have the remainder of place/sequence.length.

5 % 1 = 0 // because 1 divides 5 (or any other number perfectly)
10 % 3 = 1 // Attempting to divide 10 by 3 would leave remainder as 1
like image 104
Amresh Venugopal Avatar answered Oct 04 '22 09:10

Amresh Venugopal