0

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    `newToDo` is not used in `paintTodo`. You’re passing a function argument. You may want to go through a [tutorial](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Functions#function_parameters) again. See [Is JavaScript a pass-by-reference or pass-by-value language?](/q/518000/4642212). – Sebastian Simon Nov 19 '21 at 07:23
  • 1
    Scope is something related to **variables**, not actual objects... a single object can be bound to any number of variables with different scopes. – GACy20 Nov 19 '21 at 07:51
  • I updated the code to be a [mcve] – mplungjan Nov 19 '21 at 07:52

1 Answers1

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.

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • Additionnal half-unrelated explanation: if the variable passed to the function is an array or an object, a reference to that object will be copied, as in "Here is the link the the Google Docs document"; the link is copied, but the real document accessed by both our links is the same and can therefore be edited by one of us for both our versions. – SteeveDroz Nov 19 '21 at 07:51
  • now I understand the concept, thank u for ur kind explanation. – chohanwool Nov 19 '21 at 08:38