Inaccurate array output. Need to understand why


[Click Here for link to problem exercise]

The exercise passed me on my code and I understand a great deal of what is going on however I do not have a solid understanding of why my code, when ran, prints not only the letters of my name but also continues to after completing it, cutting some of my name off and also stating undefined variables. I can't bring myself to continue to the next part until I know exactly why.

/*jshint multistr:true */
//variables assigned
var text = "My name is bobby"
var myName = "bobby"
var hits = []

//first loop
for(var i = 0; i < text.length; i++) {
    if(text[i] === "b") {
        //second loop
        for(j = i; j < (i + myName.length); j++){
if(hits === 0) {
    console.log("Your name wasn't found!");
else {


After studying the code for a while I am assuming the first loop continues after the if function has been fulfilled so I am led to believe if I can create a false after the second loop has completed to stop the first loop I should only see b,o,b,b,y. If this is true however I still do not understand what parts are undefined.


bobby contains multiply b's. so the if statement is true multiply times. Giving undefined since you are going out of index, use a uppercase B to prevent this:

var text = "My name is Bobby"
var myName = "Bobby"
if(text[i] === "B")

string comparison is case-sensitive.


That is incredible! Something so simple! Thank you for the quick solution, I will do my best to keep this in mind in the future. If it is not too much of a bother I would like to ask: Could you elaborate a little more on "going out of index"? And thank you so much for your help I spent at least an hour breaking it down and trying to understand the recognition of an undefined while thinking of a way to end the loop.


lets say i have an array or string, doesn't matter:

example = "hello"
example = ["h","e","l","l","o"]

you can access a certain letter using index:


will be l. But if you have example[6] you have a problem. Because the o is indexed 4, at index 5 and 6 and higher is nothing.

As a safeguard, the push function pushes undefined (the ones you saw in your output) into the array, instead of crashing.

The reason this happened, is because bobby has 3 b's. The first one is the one you want to have, at the second and third one, the loop is going out of index


Perfect explanation! I understand it well now thank you!!!! That was bugging me bad, I am glad to know :slight_smile: Thank you for your time!