javascriptreturngoogle-chrome-console

Why is my function returning this strange output?


I am trying to write a function that takes in an integer as input and determines how many dots exist in a pentagonal shape around a center dot on the Nth iteration. I was able to solve the challenge, but I was receiving a strange output from the google chrome console when testing my code and I don't understand why.

This was the original code that kept giving me an error (errors shown in the image link below)

function sides(num) {
    total = 1;
    for (let i = 2; i <= num; i++) {
        top = 1;
        sides = (i - 1) * 4;
        bottom = i - 2;
        total += top + sides + bottom;
    }
    return total;
}

Then I changed it to this, which worked fine:

function pentagon(num) {
    total = 1;
    for (let i = 2; i <= num; i++) {
        answer = (((i - 1) * 4) + 1) + (i - 2);
        total += answer

    }
    return total;
}

But I don't see why they are different. All I did was consolidate the math of top, bottom, and sides into one line called answer. I don't understand why the first function worked but the second didn't, and I also don't understand the output that the first function was giving me. If anyone could explain these two things to me I'd greatly appreciate it, thank you.

enter image description here


Solution

  • You should use var, const or let keywords, otherwise your variables will mess with variables that are globally set (such as top).

    function sides(num) {
        let total = 1;
        for (let i = 2; i <= num; i++) {
            const top = 1;
            const sides = (i - 1) * 4;
            const bottom = i - 2;
            total += top + sides + bottom;
        }
        return total;
    }
    

    Edit: As @Matthias pointed out:

    window.top (MDN) refers to the top-most window (applicable in nested iframes). Without the keyword, the variable is just set as a property of window. And it's read-only