Understanding a piece of code

Tell us what’s happening:

Hi,

After a couple of hours struggling with this one I finally got it right but the line of code that was missing which is: " arr[i] = arr[j] = NaN; " I cannot understand how works, can you help me please?

Your code so far

  var sum = 0;

  for (var i=0; i < arr.length - 1; i++) {
    for (var j=i+1; j < arr.length; j++) {
       
        if (arr[i] + arr[j] === arg) {
            sum += i + j;
            arr[i] = arr[j] = NaN; 
        }
    }
  }

  return sum;
}

pairwise([1, 1, 1], 2);```
**Your browser information:**

Your Browser User Agent is: ```Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36```.

**Link to the challenge:**
https://www.freecodecamp.org/challenges/pairwise

Hi, randell my initial code was:

var sum = 0;

for (var i=0; i < arr.length - 1; i++) {
for (var j=i+1; j < arr.length; j++) {

    if (arr[i] + arr[j] === arg) {
        sum += i + j;
      
    }
}

}

return sum;
}

Since the code wasn working I was looking and found a similar solution with arr[i] = arr[j] = NaN; at the end and finally worked.

I still don t understand why I have to add the assigments at the end, sorry im a newbie :blush:

arr[i] = arr[j] = NaN

This piece of code, why we have to make this assigment, that´s my question, otherwise the result only adds the indexes one time, and honestly i dont know why.

While iterating through arr, the only time sum changes, is if arr[i] + arr[j] is equal to arg. By assigning the value NaN to each of these elements in arr, these elements can not be used again to change the value of sum. Why? Because NaN + anything is NaN and when you compare NaN to any value, it will always be false which prevents the if statement code block from add the i and j values to sum.

1 Like

Thank you Randell, I finally got it