My web browser is crash when I input my code


#1



Hi, when I tried to submit my exercise suddenly my web browser is crash and ask me to stop the page as like picture above. Is something wrong with my code? Please help...


var text = "ierfan ierfan Irfan ierfan Irfan";

var myName = "Irfan";

var hits = [];
for ( var i = 0; i < text.length; i++) {
    if (text[i] === "I") {
        for ( var j = i; i < (j + myName.length); j++) {
            hits.push(text[j]);
        }
    }
};

This is my code that I submit...


#3

You have wrong condition for second for loop:

for ( var j = i; i < (j + myName.length); j++) {
   hits.push(text[j]);
}

In your case text[i] === "I" when i = 14. So,

for(var j = 14; 14 < (j + myName.length); j++) { ... }

// and
14 < (j + myName.length) // 14 < (14 + 5) = 14 < 19

// finally, j++
14 < (j+1 + myName.length) // 14 < (15 + 5) = 14 < 20

As you can see, you have infinite loop. To resolve this problem you just need replace i with j:

j < (i + myName.length);

because second for loop works with j variable as an iterator, not i.


#4

Ahh that's why my web browser is crash... Thank you denys for your revelation. I think I understand now... :grin:


#5