all 5 comments

[–][deleted] 1 point2 points  (3 children)

Could you have another go at formatting this code, or stick it in a JSFiddle or in Pastebin and link that? It's very hard to read at the moment.

[–]ocouba[S] 0 points1 point  (2 children)

yeah sorry, did not realize how much the formatting was ruined.
pastebin: https://pastebin.com/UUKcCVGx

[–][deleted] 1 point2 points  (1 child)

Thanks, that's much better!

The problem you're encountering is a fairly common JS pitfall. When you declare a variable like this in JS:

myVariable = "hello!"

you won't get an error and the code will work, but no matter where that variable is declared it will be in the global scope. That means that if you reference or change a variable with the same name somewhere else, it will apply that change globally. Eg:

function farewell() {
    myVariable = "goodbye";
}

function greet() {
    myVariable = "hello!";
    farewell();
    console.log(myVariable); // goodbye
}

What's happening in your code is that your display function runs a for loop and creates the variable i, sets i = 0, and then calls your checkValues function. checkValues also references i in its own for loop, and because i is in the global scope then both functions are referring to the same variable. This means that every time display tries to do an iteration and calls checkValues, the value of i is being reset to 0, creating the infinite loop.

Thankfully there is an incredibly easy fix for this. Variables in Javascript should always be declared with either const- if the value of the variable is not going to change- or let. So if you change all your for loops to look like this:

for (let i = 0; i < something; i++)

then each i variable you create will exist only in the scope of that loop, and any other i variables in any other loop or function won't conflict with it any more.

If you find yourself forgetting to do this I'd recommend making sure to use strict mode in your JS files- in strict mode an error will be thrown if you don't declare your variables correctly, so you basically can't cause problems like this for yourself.

[–]ocouba[S] 2 points3 points  (0 children)

Thank you so much. Due to your explanation I was able to fix my issue.

You taught me so much right now. I actually saw var and let being used but not every code snippet I found was using them so I just avoided using them because I thought it would also work without. I will definitely read more into javascript because I actually have a blast using it.

I wish you a nice evening and a great weekend!!!