Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda