javascriptif-statementbuttoninnertext

Currently having an issue with my If else function in JavaScript. The if statement works but the else statement does not


Hi so this is a very basic issue that I'm currently not able to solve. Using only JavaScript I'm trying to create a like button that changes it text content from an empty heart to a full heart while also having an increment and decrement functionality. I am using unicode as the text content.

My issue is that the if statement seems to be working just fine since on a click it does go from an empty heart to a full heart while also incrementing, but the else statement doesn't seem to be. It just seems to be stuck in the full heart and only keeps incrementing on click.

I've tried using else if as well but it doesn't seem to work either.

Any advice is appreciated.

let likes = Math.floor(Math.random() * 100)+1;
const likesDiv = document.createElement("span");
const likesButton = document.createElement("button");
likesDiv.appendChild(likesButton);

const emptyHeart = '\u2661';
const fullHeart = '\u2665';
likesButton.textContent = emptyHeart;
likesDiv.innerText = `${likes}`;

likesButton.addEventListener("click", toggle)
    
    function toggle() {
      if (likesButton.textContent = emptyHeart) {
        likesButton.textContent = fullHeart
        likes++;
        likesDiv.innerText = `${likes} `;
      }
      else{
        likesButton.textContent = emptyHeart;
        likes--;
        likesDiv.innerText = `${likes} `;
      }
    };

Solution

  • Comparisons are done with double equal sign ==. A single equal sign assigns the value to the variable and returns the assigned value. JavaScript will auto-cast this into a boolean, resulting in stepping into the if block for all truthy values.