Search code examples
javascriptfunctional-programmingimmutabilityfuncmutability

How to deal with immutable objects in javascript?


I'd like my objects to be immutable but copying the same object like hundred times doesn't make much sense to me.

const arr = [1,2,3]
const arr2 = [...arr, 4]
const arr3 = [...arr, 5]

What if I have to copy it more times? How can I deal with it? I don't wanna declare each time new const for an object for copying. How can I use it later in my program?

For example I've got a simple app that changes values in array and puts it into html.

const arr = [10,20];
foo(arr.map(x => x + 5))

What if I wanted to map it again with its new values? And then again and again? How would I deal with this problem?


Solution

  • I don't wanna declare each time new const for an object for copying.

    You can avoid writing const for every declaration using these strategies. There are probably more, depending on your exact use case.

    const arr = [1, 2, 3];
    const [arr2, arr3] = [[...arr, 4], [...arr, 5]];
    
    console.log(arr2);
    console.log(arr3);

    const
      arr = [1, 2, 3],
      arr2 = [...arr, 4],
      arr3 = [...arr, 5];
     
    console.log(arr2);
    console.log(arr3);