JS interview in 2 minutes / value vs reference

Question:
Explain passed by value and passed by reference.

Quick answer:
In JavaScript, all primitive values are passed by value, but all non-primitive types are passed by reference. This means you can change params and this change will be isolated (w…


This content originally appeared on DEV Community and was authored by Nikita Kozlov

Question:
Explain passed by value and passed by reference.

Quick answer:
In JavaScript, all primitive values are passed by value, but all non-primitive types are passed by reference. This means you can change params and this change will be isolated (with no side-effects).

Longer answer:
So the primitive types in JavaScript are undefined, Boolean, String, and others.

Structural types (non-primitive) are Object and Function. Needed to mention that arrays and other structures have an Object type too.

This means when you pass some value to the function its behavior will depend on its type.

carbon (4)

Real-life example:
In real-life apps, you need to be extra careful when changing any of provided function params, because debugging issues like this can be super tricky and time-consuming.

carbon (5)

This is how you can fix this issue:

carbon (3)

Other things to read:

Also, I will post more fun stuff here and on Twitter let's be friends ?


This content originally appeared on DEV Community and was authored by Nikita Kozlov


Print Share Comment Cite Upload Translate Updates
APA

Nikita Kozlov | Sciencx (2021-04-25T09:39:26+00:00) JS interview in 2 minutes / value vs reference. Retrieved from https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/

MLA
" » JS interview in 2 minutes / value vs reference." Nikita Kozlov | Sciencx - Sunday April 25, 2021, https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/
HARVARD
Nikita Kozlov | Sciencx Sunday April 25, 2021 » JS interview in 2 minutes / value vs reference., viewed ,<https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/>
VANCOUVER
Nikita Kozlov | Sciencx - » JS interview in 2 minutes / value vs reference. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/
CHICAGO
" » JS interview in 2 minutes / value vs reference." Nikita Kozlov | Sciencx - Accessed . https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/
IEEE
" » JS interview in 2 minutes / value vs reference." Nikita Kozlov | Sciencx [Online]. Available: https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/. [Accessed: ]
rf:citation
» JS interview in 2 minutes / value vs reference | Nikita Kozlov | Sciencx | https://www.scien.cx/2021/04/25/js-interview-in-2-minutes-value-vs-reference/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.