DEV Community

Ryan Pierce
Ryan Pierce

Posted on

Assigning a Variable May Not Always Be As It Seems

So recently while writing some code, I ran into an interesting problem that kind of boggled my mind. Pictured below is the code snippet that I will be discussing today.

function handleSubmit(e) {
    e.preventDefault();
    let totalVotes = document.querySelector('#vote-count').textContent

    parseTot = parseInt(totalVotes)
    parseTarg = parseInt(e.target.votes.value)
    totalVotes = parseTot + parseTarg

    document.querySelector('#vote-count').textContent = totalVotes

    currentCharacter.votes = totalVotes

    patchCurrentCharacter(currentCharacter)
}

Enter fullscreen mode Exit fullscreen mode

The section of code I would like to discuss is the first 6 lines of my function “handleSubmit”. On the second line, I create a variable called totalVotes in which I then assign the value of document.querySelector(‘#vote-count’).textContent. So why, then, do I have to restate that exact thing on the sixth line? Why doesn’t the 5th line cover what needs to be stated on line 6, and even then, why couldn’t line 6 run as totalVotes = totalVotes?

This is where the title of my post comes in. On my second line, all I am doing is assigning my totalVotes variable the literal text content at that location, which could be anything. If I console.log(totalVotes) here, I get whatever that text content is, I don’t get back “document.querySelector(‘#vote-count’).textContent. This means that I can't alter that html elements text content with my totalVotes variable, because it isn't linked to that element necessarily, it is only assigned that elements text content.

As someone new to programming, this was difficult to catch in code, and was almost just as difficult to understand while someone explained it to me. However, I feel like this particular case is something that requires a sort of Eureka moment: a moment where you don’t understand initially, but once you do, it makes total sense.

Hopefully I was able to help you towards your Eureka moment if you are also struggling with this concept!

Top comments (0)