DNA Pair Algorithm -- Help Understaning .forEach Behavior

Hi all! So I have my code working (yay!) but it appears as though it is not executing top-to-bottom as I expect, and I’m not sure why. :confused:

Here’s my solution: http://bit.ly/2jWY0Iu

In the middle I have a “sanity check” console log that breaks the two steps in half, but when it runs it is ~actually~ logging as if the .forEach section of the code below it has already run (adding the second letter pair to the sub-array), thus is giving me the final answer.

Why does this happen? Does .forEach have a special flag about how it is handled by the interpreter?
I’ve dug around on the .MDN and I’ve only found that .forEach cannot be chained.

Hi. Could you paste your code here instead? Your link only shows the first seven lines of your code.

Sorry about that!

Here’s my code directly, and a jsfiddle that should work https://jsfiddle.net/InkAnt908/4hzL7us6/1/

function pairElement(str){
var arr = [];
var tempArr = [];

//Step 1.
//Take str, push each char to a sub-array,
//Then push that sub-array into the main array & reset
for (var i = 0; i<str.length; i++){
tempArr.push(str[i]);
arr.push((tempArr));
tempArr = [];
}

//Up to this point, we ~should~ have arr = [["G"],["C"],["G"]]
console.log("Sanity check:",arr);

//Step 2.
//Loop through each subarray, add the companion letter to it
arr.forEach(function addPair(arr){
//console.log(arr[j],"is:",arr[j]);
while (arr.length <= 1){
if (arr[0] == "A"){
   arr.push("T");
  }
else if (arr[0] == "T"){
   arr.push("A");
  }
else if (arr[0] == "G"){
   arr.push("C");
  }
else if (arr[0] == "C"){
   arr.push("G");
  }
else{
 console.log("Something is broken :(");
 }
console.log("Add pair done, returning:",arr);
return arr;
}
});

console.log("DONE!",arr);
return arr;
}

pairElement("GCG");

It doesn’t seem to be the case. Look at this.
https://repl.it/FY57/1

I think it has something to do with the browser’s console (like, it doesn’t give you a snapshot of what the array looks like before you run .forEach, but instead gives you a “link” to the array).

1 Like

Oh wow, that’s interesting!

On that linked module it works as you described, but in the FCC courses, jsfiddle, and a local page with tags it gives me the original result: http://imgur.com/rcJ0w2r

It does the same thing in Firefox, as well… weird.