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

151
Visualizações
Why does a function recognize a const declared in another function?

I'm new to JS and in the JS code below, the const newTodo is used in handlTodoSubmit() and I'm using it as an argument of paintTodo().

what I know is: when I'm using a var in specific function, that var can only use in the function which it contained. but the paintTodo() is using newToDo value in span.innerText

How can this happen?

const toDoForm = document.getElementById("toDoForm");
const toDoInput = document.getElementById("toDoInput");
const toDoList = document.getElementById("toDoList");

function paintTodo(list){
    const li = document.createElement("li");
    const span = document.createElement("span");
    span.innerText = list;
    li.appendChild(span);
    toDoList.appendChild(li);
}

function handleTodoSubmit(event){
    event.preventDefault();
    const newToDo = toDoInput.value;
    toDoInput.value = "";
    paintTodo(newToDo);
}

toDoForm.addEventListener("submit", handleTodoSubmit);
<form id="toDoForm">
  <input type="text" id="toDoInput" />
  <input type="submit" />
  <ul id="toDoList"></ul>
</form>

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

0

Your const newToDo is declared in handleTodoSubmit and only used in that context. As you can see, there is no call to newToDo in paintTodo.

Nontheless, the entity represented by newToDo and the one represented by list contain the same value (even though they are not the same)! In programming languages (a good number of them anyway), if you pass a variable or a constant to a function, that said function will copy it and use that copy (as in "I send you an e-mail with the PDF attached", you will only have a copy of my PDF).

The newToDo variable stays in handleTodoSubmit, but there exists a copy of it called list in paintTodo.

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