Home > Mobile >  Modify and write an input html value in javascript
Modify and write an input html value in javascript

Time:09-18

I'm working on a fronted calculator project but i don't really understand a strange behavior in Javascript. This is my script:

const keys = document.querySelectorAll(".number");
const screen = document.querySelector("#screen");
let number = screen.value;

keys.forEach((key) => {
  key.addEventListener("click", (event) => {
    let refresh = (number  = key.textContent).toString();
    console.log(number);
    screen.value = refresh;
  });
});

Someone can tell me why if i change this line

screen.value = refresh;

with this one

number = refresh;

my value on the screen does not update despite in my console it is updating? Aren`t these two different names to call the same thing?

Thank you

CodePudding user response:

This is caused by string variables being assigned a value instead of a reference. This means that when you call let number = screen.value it only sets number to the value screen.value has at that moment. But if you change one of them, the other remains the same.

This is true for primitive types like numbers, strings and booleans. Objects and array variables are assigned references, meaning that changing the object through one variable will be reflected in all other variables pointing to the same object.

CodePudding user response:

This is because you are using this line:

console.log(number);

So you will first print 'number' variable and later you will update the value of this variable, so this is the problem

if you want to solve this you have to invert the order of the lines something like this:

screen.value = refresh;
console.log(number);

I hope I've helped ;)

  • Related