←back to thread

498 points azhenley | 1 comments | | HN request time: 0.201s | source
Show context
hackthemack ◴[] No.45771794[source]
One area that I like to have immutability is in function argument passing. In javascript (and many other languages), I find it weird that arguments in function act differently depending on if they are simple (strings, numbers) versus if they are complex (objects, arrays).

I want everything that passes through a function to be a copy unless I put in a symbol or keyword that it suppose to be passed by reference.

I made a little function to do deep copies but am still experimenting with it.

  function deepCopy(value) {
    if (typeof structuredClone === 'function') {
      try { return structuredClone(value); } catch (_) {}
    }
    try {
      return JSON.parse(JSON.stringify(value));
    } catch (_) {
      // Last fallback: return original (shallow)
      return value;
    }
  }
replies(3): >>45771864 #>>45772569 #>>45773187 #
DougBTX ◴[] No.45773187[source]
> I want everything that passes through a function to be a copy unless I put in a symbol or keyword that it suppose to be passed by reference.

JavaScript doesn’t have references, it is clearer to only use “passed by reference” terminology when writing about code in a language which does have them, like C++ [0].

In JavaScript, if a mutable object is passed to a function, then the function can change the properties on the object, but it is always the same object. When an object is passed by reference, the function can replace the initial object with a completely different one, that isn’t possible in JS.

Better is to distinguish between immutable objects (ints, strings in JS) and mutable ones. A mutable object can be made immutable in JS using Object.freeze [1].

[0] https://en.wikipedia.org/wiki/Reference_(C%2B%2B)

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

replies(2): >>45773535 #>>45774903 #
1. hackthemack ◴[] No.45773535[source]
I guess in javascript world, the phrasing I am looking for would be

I wish all arguments were copies unless I put some symbol that says, alright, go ahead and give me the original to mutate?

It seems like this way, you reduce side effects, and if you want the speed of just using the originals, you could still do that by using special notation.