Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
At least things are better than you still not seeing anything wrong with that.
That's what improvement is all about. -
Why?! Aren't arguments not supposed to be changed? I just don't see any use for it.
Can you explain? -
@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. -
@juliandroid uh, I'm kind of baffled by this detailed explanation.
Thanks for taking the time to explain!
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.
rant
js impure_functions old_code