Forgot to comment my code. Why does this work?

Here are the instructions:

We’ll be rebuilding the native .join array method. The join function should work as follows:

// If the input is empty, return an empty string
join([]) // ''

// If there is no separator, separate by commas
join([ 'a', 'b', 'c' ]) // 'a,b,c'

// If there is a separator, separate by that string
join([ 'a', 'b', 'c' ], '-') // 'a-b-c'

// If there is only one item, return just that item
join([ 'a' ], '---') // 'a'

I’m just a bit confused on this line:

if (separator && array[i] !== array[array.length-1])

Here is my code:

function join (array, separator) {
    let str = '';
    for (let i = 0; i < array.length; i++) {
      str += array[i];
      if (separator && array[i] !== array[array.length-1]) {
        str += separator;
      } else if (array[i] !== array[array.length-1]) {
        str += ',';
      }
    }
    return str;
  }

Roughly in English, that means, “if there is a separator, and the ith element in the array is not the last element, do the following…”

Thanks man. Appreciate it.

You are insane at this. Truly. I can only hope at some point I get that good.

Also, if you find time, could you comment that regular expression using RegExp? I’m trying to learn Regex as it seems to be the best way to solve a lot of things that I tend to complicate.