Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!