Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Modify and write an input html value in javascript

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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 ;)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda