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>
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.