Understanding a piece of code

Understanding a piece of code
0.0 0

#1

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

#2

Since you wrote this line of code, what were you thinking it was going to do?

It would have been the same as writing:

arr[j] = NaN;
arr[i] = arr[j]; 

Assignment always works from right to left, meaning a value on the right of the assignment operator gets assigned to what is on left of the assignment operator.


#3

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:


#4

I am not sure what you mean. You do not understand why you have to add the assignment at the end of what?


#5

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.


#6

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.


#7

Thank you Randell, I finally got it