Parameter passing in JavaScript
Many programming languages use two different methodology while working with parameters send to functions.
- Pass by reference which reference of parameters are sent instead of value
- Pass by value which value of parameter is sent instead of reference
In javascript, the methodology changes according to your data type.
- Primitive types such as string, boolean or number is sent by passing by values which means your reference is not copied but your value.
- For object type parameters, pass by reference method is used. Because of your reference is copied, any modification in your function will effect original object.
Let’s try it with below code snippet
How to deal with object references
Object.assign
Object.assign is a new feature of ES6 standarts. Using this function, you can create new an object by copying source object’s properties. Let’s test it by modifying above example.
Const: This function does not make a deep copy as shown on above example. It only copies of values of properties except inner objects. Inner object’s reference is copied.
Const: IE does not support that function. Pollyfill must be used
Lodash
Another useful function which is called cloneDeep can be used to full copy of all properties in an object.
Advise: Import only used lodash function instead of importing all lodash functions in your code for not to oversize your bundles.
ImmutableJS
Immutable js is a library developed by facebook and solves our most of the problems while working on objects.
References
If you like my articles, you can support me by clapping and following me.
I’m also on linkedin, all invitations are welcome.
