Calculator in JS , scope or immutable issue?

Hi there,

I am working on creating a calculator in JavaScript & ran into this issue. The first code is not working, while somehow the second one is.

What the code is doing is changing the number from the calculator display (0 by default) to the passed in value as long as it’s not an action (-/+x=).

Can anyone help me find out what exactly the difference here is? Is it because the “const display” is immutable and can’t be changed by saying display = value or is there more to it? It’s also not working when I change it to let or var.

Thanks, looking forward to learning the solution!

const calculator = document.querySelector(".calculator");
const keys = calculator.querySelector(".inputKeys"); 
const displayValue = calculator.querySelector(".display");

keys.addEventListener("click", e => {   
  if (e.target.matches("button")) {       
    const keys = e.target;               
    const action = keys.dataset.action;   
    const value = keys.textContent;      
    const display = displayValue.textContent;

  if(!action) {
      if (display === "0"){
        display = value;
        alert("you pressed a number");
        alert(value);
      }
    }
  }
})

const calculator = document.querySelector(".calculator");
const keys = calculator.querySelector(".inputKeys"); 
const displayValue = calculator.querySelector(".display");

keys.addEventListener("click", e => {   
  if (e.target.matches("button")) {       
    const keys = e.target;               
    const action = keys.dataset.action;   
    const value = keys.textContent;      
    const display = displayValue.textContent;

  if(!action) {
      if (display === "0"){
        displayValue.textContent = keys.textContent;
        alert("you pressed a number");
        alert(value);
      }
    }
  }
})

Can you share the codepen code?

Yes, here it is: https://codepen.io/robinlutterveld/pen/MZOreQ

    const display = displayValue.textContent;

and

        display = value;

const cannot be reassigned a value. I did try it with both var and let and it works for me.

1 Like

Great, thank you very much.