find helper JavaScript

I have found this script on the Mozilla Development Network as an example.

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

Could you explain me what the double "+" means right after the "start"? Will it change the value of the start variable?

Thank you

Upvotes: 1

Views: 57

Answers (2)

Rares Matei
Rares Matei

Reputation: 286

The double "+" after a variable means that it will increase that variable by 1 after it has used it in the statement.

So in your case element % start++ < 1 is equivalent to element % start < 1; start = start+1;

On the other hand, having the "++" before the variable, means it will first increment the variable, and then execute the statement.

Here are some examples of this behaviour:

var a = 1;
var b = a++;
console.log(b); // 1
console.log(a); // 2

var c = 1;
var d = ++c;
console.log(d); //2
console.log(c); //2

var test = 2;
if (8 % test++ < 1) {
  console.log("will log");
}

test = 2;
if (8 % ++test < 1) {
  console.log("will NOT log");
}

Upvotes: 1

Harald Nordgren
Harald Nordgren

Reputation: 12409

This is the same as

var old_value = start;
start = start + 1;
if (element % old_value < 1) {
...

Read the value of the variable and then increase it by one.

Upvotes: 2

Related Questions