1

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

  • 1
    It will increment the variable by 1 and assign the result to itself. You can read more about the **increment operator** [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()) – mrlew Feb 04 '17 at 19:36
  • Possible duplicate of [++someVariable Vs. someVariable++ in Javascript](https://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript) – Chiri Vulpes Jul 01 '17 at 06:19

2 Answers2

2

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.

Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
1

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");
}
Rares Matei
  • 286
  • 1
  • 12