Search code examples
javascriptarraysfor-looppalindrome

Can someone explain what's going on in this for loop?


Also please include a tracetable that shows the values of each variable at each position. Thanks. When it returns true, it says that the array is a palindrome. When it returns false, it says that the array is not a palindrome. The code works, but I just need an explanation of why or how it works.

var x = readNumberOfEntries();
                var w = new Array(x);
                for (var y = 0; y < x; y++) {
                    var z = Number(prompt("Enter entry"));
                    w[y] = z;

                }
                var r = w.length;
                for (var i = 0; i < (r/2); i++) {
                    if (w[i] !== w [r-1-i]) {
                        return false;
                    }
                    return true;
                }
            }

Solution

  • First for-loop fills an array of length x with user entered values.

    Second for-loop checks for array like this [1,2,3,3,2,1]. So it checks wether the array is reversev in the second half.

    Though because of the return the for-loop will be canceled at first run.

    So if the first entry of the array equals the last it will return true, otherwise false.