8

So, today I revisited my 5 months old code and was like "What? Did I really wrote this horrible code?" 😐️ 🙂️ 😃️🔫️

```js
setState((initVal) => {
initVal.food = 'burger';
return initVal;
});
```

The function above change its argument's value, which is terrible thing to do, since it will also change the original value passed to the function. A variable's value for example. Making it an impure function.

Comments
  • 7
    At least things are better than you still not seeing anything wrong with that.
    That's what improvement is all about.
  • 1
    @alcatraz627 Absolutely correct! one up!
  • 0
    Why?! Aren't arguments not supposed to be changed? I just don't see any use for it.
    Can you explain?
  • 6
    @Ranchu If you wrote codes in C/C++ before, you can know that structures and objects are stored and the variable you valued is only an offset.
    In Javascript or some other advanced languages, although there's "no pointer" when programming, the var stores an offset.
    So when you changed a member of an object, you changed the original object's member.

    If your argument is INT:
    function a(b){
    b+=1;
    return b; // useless in this case
    }
    var z=3;
    a(z);
    console.log(z); // 3

    if it is an object:
    function a(b){
    b.m=0;
    return b; // useless in this case
    }
    var z={m:3}
    a(z);
    console.log(z); // {m:0}

    in case 1, z is an integer, and it will make a copy of z as b in the function.
    in case 2, z is an object, it stores only an offset like C/Cpp, so it won't make a copy, operate it in the function is the same as modifing it outside. It will make a copy of the offset, and two offsets is in a same value, point to the same location in RAM where the object stores, so you're operating the same thing.
  • 2
    @juliandroid uh, I'm kind of baffled by this detailed explanation.
    Thanks for taking the time to explain!
  • 0
    Right. But I'm already feeling unwell by seeing "setState" 😅 Vue it. 😏
Add Comment