0

quick question:

I want to use spread operator to push elements in my to-dos array. It works, when i declare an array and use it in creator function with spread syntax in same js file.

However, i want to use a dedicated main.js or helper.js file to store my to-dos array.

in my helpers.js i have

let toDoArray = []

...

export { inputItems, toDoArray, toDosWrapper };

in my newToDo.js i have

import { inputItems, toDoArray } from './helpers.js';

...

function addToDoArray(toDo) {
  toDoArray = [...toDoArray, toDo()];
  console.log(toDoArray);
  printToDos(toDoArray);
}

...

So it throws this error:

Uncaught TypeError: "toDoArray" is read-only
Kerem Z
  • 13
  • 5
  • This has nothing to do with spread syntax. When you import a variable, it is effectively `const`. – Pointy Sep 04 '21 at 19:47
  • So there is no way to use an imported variable as a writable variable? – Kerem Z Sep 04 '21 at 19:49
  • You can a) mutate the object instead of reassigning the variable, i.e. `toDoArray.push(toDo())` or b) call a function *inside the module* that reassigns `toDoArray` (which also will be visible in the importing module, as the chosen alias is just a reference to the exported variable) – Bergi Sep 04 '21 at 21:53
  • Yes, i did it via push() function. But javascript makes me always surprised. At the end of the day i mutate it via push(), even though is read-only. Very interesting. – Kerem Z Sep 05 '21 at 07:14

0 Answers0