Search code examples
javascripthtmlfunctionincrementtemplate-strings

i need to increment a number in a classList template string javascript


hello friends I got a hard one and I'm a bit in a pickle in my blackjack game I create images(of the cards) and the values come from the .PNG name from a list in an object. what I want to do is be able to create a class on those images to be able to use the classList.contain() method in a other function. it seems to work but the number doesn't increment every time I call the function. All the cards have the same class.

function showCard(activePlayer, card) {

if (activePlayer.score <= 20){
    
    let cardImage = document.createElement("img")
    function incrementNumber(number){
        number = number++
        return number
    }
    //increment the number of the class
    cardImage.classList.add(`images${incrementNumber()}`)
    cardImage.src = `images/${card}.png`
    document.querySelector(activePlayer["div"]).appendChild(cardImage)
    hitSound.play() 
} 

} I know i most likely forgot a simple thing but i cannot put my finger on it. I added a number in the ${incrementNumber(1)} still keeps giving me the same images class for all images. thank you for all you're help!


Solution

  • The ++ (increment) operator can be confusing sometimes.

    In your case, you are using it, but you are also assigning its return value back to the number. The easiest solution is not doing that assignment (changing number = number++ for just number++)

    It also looks like number should be a global variable, not a parameter passed to the incrementNumber function.

    The more interesting part to the problem though, is why the code does not work. This is due to how the ++ operator works. When you place it after a variable name (eg number++) JavaScript will effectively do this:

    var temp = number;
    number = number + 1;
    return temp;
    

    It increments the number variable by 1, but it returns the previous value of the variable. In your case, when assigning the result of number++ back to number, the increment operation will basically be cancelled out.

    Also, note that you can place the ++ operator before a variable name (like ++number). This will not return the original value of the variable, instead returning the new (incremented) value.