{"resource":{"author":{"id":"h2so9H8jPMmgUKGghoNl","name":"Yomesh Gupta","username":"yomeshgupta"},"content":{"link":"https://devtools.tech/understanding-call-by-value-vs-call-by-reference-in-javascript/","difficulty":1,"domain":2,"type":1,"isInternal":true,"body":"In this post, we will try to understand how JavaScript works a bit different than other programming languages when it comes to data manipulation. We will primarily look at two fundamental ways of manipulating data i.e. `Call By Value` and `Call By Reference`.\n\n### Data Types\n\nTo start with, we need to know different data types in JavaScript. It can be divided into two groups, `Primitive` and `Non-Primitive`.\n\n```\nPrimitive\nNumber\nString\nBoolean\nUndefined\nNull\n\nNon-Primitive\nObject\nArray\n```\n\nKnowing these data types will help us understand better how they are processed by the JavaScript interpreter.\n\n### By Value\n\nWhen a variable is passed by value to a function then a copy of the variable is passed. The original and the copy are two independent values that are stored separately. Any changes made to the copy inside the function does not change to the original value. It holds for all primitive data types. However in JavaScript, **everything is passed by value** (More on this later).\n\n```js\nvar original = 10;\n\nfunction modify(copy) {\n  copy += 20;\n  return copy;\n}\n\nvar modified = modify(original);\nconsole.log(original, modified); // 10 30\n```\n\nHere, we did pass the variable to the function and made some changes to it. However, the original value remained the same due to the fact function scope maintained a local copy of the passed argument and all changes were made to that copy which does not change the original value.\n\n### By Reference\n\nWhen a variable is passed by reference then there is only one actual copy of the value. There can be multiple references to that value but never duplicate(s) of that value.\n\n```js\nvar first = { name: \"Yomesh\" };\nvar second = first;\n\nconsole.log(first, second); // { name: 'Yomesh' } { name: 'Yomesh' }\n\nsecond.name = \"Ajay\";\n\nconsole.log(first, second); // { name: 'Ajay' } { name: 'Ajay' }\n```\n\nAs you can see in the above code snippet the `second` variable holds a reference to the value (assignment made by reference). Due to this fact, changes made to the value by one reference are reflected across all the references. A similar situation happens when a variable is passed by reference to a function.\n\n```js\nvar person = { name: \"Yomesh\" };\n\nfunction modify(person) {\n  person.name = \"Ajay\";\n  return person;\n}\n\nvar newPerson = modify(person);\nconsole.log(person, newPerson); // { name: 'Ajay' } { name: 'Ajay' }\n```\n\nThe variable person was passed by reference to the function and changes were made to the value using the passed reference. Hence, it is visible outside the function also i.e. original value is modified. It holds for all non-primitive values (Objects and Arrays).\n\n> Note: The following is very important. So, read it carefully and understand it.\n\nThe basic rule would be that the primitive types are passed by value and the non-primitive types are passed by reference. However, earlier, it was mentioned that in JavaScript **everything is passed by value** but our current findings contradict that! Well, not exactly, in terms of non-primitive types, variables are also passed by value. However, the passed value is a reference to the variable rather than the variable itself.\n\n```js\nvar person = { name: \"Yomesh\" };\n\n// passed by value where value is a reference (Step 1)\nfunction modify(newPerson) {\n  newPerson.name = \"Ajay\"; // original value is modified via reference (Step 2)\n}\n\nmodify(person);\n\n/** ====== Illustrations ======\n\n      ----------------------\n      | { name: 'Yomesh' } | // Step 1\n      ----------------------\n          | |\n  person ---------| |\n            |\n  newPerson ----------|\n\n      ----------------------\n      | { name: 'Ajay' } | // Step 2\n      ----------------------\n          | |\n  person ---------| |\n            |\n  newPerson ----------|\n\n**/\n```\n\nArgument `newPerson` maintains a reference to the original value due to which it can change the original value and it is reflected everywhere. However, if the reference is altered in some way then it is not visible outside.\n\n```js\nvar person = { name: \"Yomesh\" };\n\n// passed by value where value is a reference (Step 1)\nfunction modify(newPerson) {\n  newPerson = { name: \"Ajay\" }; // reference is overwritten with a reference to a new value (Step 2)\n}\n\nmodify(person);\n\n/** ====== Illustrations ======\n\n      ----------------------\n      | { name: 'Yomesh' } | // Step 1\n      ----------------------\n          | |\n  person ---------| |\n            |\n  newPerson ----------|\n\n      ----------------------      ----------------------\n      | { name: 'Yomesh' } |      | { name: 'Ajay' }  | // Step 2\n      ----------------------      ----------------------\n          | X               |\n  person ---------| X                 |\n            X               |\n  newPerson ----------|-----------------------------|\n\n**/\n```\n\n### Use-cases\n\nAs we have seen modifying via reference leads to changes in the original value. We can rectify this by creating a copy.\n\n```js{3-4}\n...\nfunction processing(input, value) {\n  var copy = [...input];\n  copy.push(value);\n  return copy;\n}\n...\nvar newPeople = processing(people, { name: 'prithvi' });\nconsole.log(people, newPeople);\n// [{ name: 'yomesh' }, { name: 'ajay' }]\n// [{ name: 'yomesh' }, { name: 'ajay' }, { name: 'prithvi' }]\n```\n\nHowever, copying via `spread operator` or `Object.assign` creates a shallow copy which can lead to further complications. Hence, it is recommended to always deep clone when you have nested values and want to modify data.\n\n```js\nvar data = { name: \"prithvi\" };\nvar people = [{ name: \"yomesh\" }, { name: \"ajay\" }];\nfunction processing(input, value) {\n  var copy = [...input];\n  copy.push(value);\n  copy[copy.length - 1].name = \"joker\";\n  return copy;\n}\nvar newPeople = processing(people, data);\nconsole.log(people, newPeople, data);\n// [{ name: 'yomesh' }, { name: 'ajay' }]\n// [{ name: 'yomesh' }, { name: 'ajay' }, { name: 'joker' }]\n// { name: 'joker' }\n```\n\nHere, in the above code snippet, even after making a copy the changes are visible outside. To fix this, we can deep clone using any suitable method.\n","languages":[],"editorConfig":{}},"stats":{"views":8908,"used":0,"likes":0},"description":"","published":true,"isActive":true,"tags":["node.js","javascript","js","call by value","call by reference","frontend fundamentals","interview questions","call by value vs call by reference"],"slug":"understanding-call-by-value-vs-call-by-reference-in-javascript---rid---7MW12KGElzTyMF7wapHw","isPremium":false,"categories":[],"requires":[],"_id":"5f1ded89cbec5f7ffc0c2fb1","title":"Understanding Call By Value vs Call By Reference in JavaScript","resourceId":"7MW12KGElzTyMF7wapHw","createdAt":1595796873207,"modifiedAt":1643114384094},"currentUser":null,"isOwner":false,"recommendations":{"questions":[{"_id":"6610e9864e1bed1edc0bc0f5","content":{"languages":["javascript","typescript"],"difficulty":4},"tags":["frontend","array","interview question","problem solving","makemytrip frontend interview question","devtools tech","tutorial","blog"],"slug":"write-a-function-to-return-the-count-of-numbers-in-an-array-or-makemytrip-frontend-interview-question---qid---cjzjsfJUP0zHb2lgPJVy","title":"Write a function to return the count of numbers in an Array | MakeMyTrip Frontend Interview Question","questionId":"cjzjsfJUP0zHb2lgPJVy"},{"_id":"636dfc99bc012474df4d3825","content":{"languages":["javascript"],"difficulty":1},"tags":["javascript","frontend","coding","devtools tech","interview questions","interview preparation","mcq","programming paradigm","tooling","mdn","js paradigm","programming questions","array slice","array methods","javscript arrays"],"slug":"what-would-be-the-output-of-the-following-code-based-on-array-slice---qid---4GsiLnGEEmLaUaoWb64V","title":"What would be the output of the following code? (Based on Array Slice)","questionId":"4GsiLnGEEmLaUaoWb64V"},{"_id":"645e244cd12c1e2402019e67","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["frontend","code","programming","lodash","polyfill","lodash once","javascript interview question","ui","ux","devtools tech","codedamn","egghead","frontend masters","problem solving","frontend interview questions","underscore","geeksforgeeks","rate limit","lodash before","limit js function invocation"],"slug":"implement-a-function-that-accepts-a-callback-and-restricts-its-invocation-to-at-most-n-times-or-lodash-polyfills-or-frontend-problem-solving---qid---ge3cwzQQrMlXt6VwDpNg","title":"Implement a function that accepts a callback and restricts its invocation to at most N times | Lodash Polyfills | Frontend Problem Solving","questionId":"ge3cwzQQrMlXt6VwDpNg"},{"_id":"5e8ce95cb2cdcd5697fea7bf","content":{"languages":["javascript"],"difficulty":1},"tags":["node.js","javascript","frontend","code","logic","variables","block scope","scoping","hoisting"],"title":"What is the output of the following code snippet? | JavaScript Output Based Question | JS Variables","questionId":"fKtjCwgbBqNJSPj4c6gX","slug":"what-is-the-output-of-the-following-code-snippet-or-javascript-output-based-question-or-js-variables---qid---fKtjCwgbBqNJSPj4c6gX"},{"_id":"64270fcb6577005718b7c555","content":{"languages":["react","html"],"difficulty":1},"tags":["javascript","frontend","ui","ux","figma","login page design","frontend projects","devkode","real world interview question","practice project","devtools tech"],"slug":"design-a-login-page-or-version-1-or-react-js-or-html-or-css-or-javascript-or-frontend-projects-for-beginners---qid---XbwRiIWYgOl8DpgCqwx6","title":"Design a Login Page | Version 1 | React.js | HTML | CSS | JavaScript | Frontend Projects for Beginners","questionId":"XbwRiIWYgOl8DpgCqwx6"}],"resources":[{"_id":"620a50051641361c7c65bd61","content":{"difficulty":4,"domain":2,"type":1,"isInternal":true},"tags":[""],"slug":"how-to-fix-errors-like-referenceerror-window-is-not-defined-in-remix-powered-web-app-or-javascript-frameworks---rid---G0OTehUXo6QQCrfykSF3","title":"How to fix errors like ReferenceError Window is Not Defined in Remix Powered Web App | JavaScript Frameworks","resourceId":"G0OTehUXo6QQCrfykSF3"},{"_id":"620406cce12bce537863eaf0","content":{"difficulty":4,"domain":1,"type":1,"isInternal":true},"tags":["javascript","remix run","social login","login with google","express","session","encryption","js fundamentals"],"slug":"add-social-authentication-to-remix-run-project-or-express-server---rid---jVwo6agJvN2oX4IegYgz","title":"Add Social Authentication to Remix Run Project | Express Server","resourceId":"jVwo6agJvN2oX4IegYgz"},{"_id":"5f1dd7cbcbec5f7ffc0c2fae","content":{"difficulty":2,"domain":1,"type":1,"isInternal":true},"tags":["node.js","javascript","frontend","frontend fundamentals","js fundamentals","interview questions","backend","backend fundamentals","webpack","inside webpack","advanced webpack","webpack defineplugin","define plugin"],"slug":"optimizing-your-javascript-bundle-or-defineplugin-webpack---rid---kvP5tP0G6isd86ALJUeh","title":"Optimizing your JavaScript Bundle | DefinePlugin Webpack","resourceId":"kvP5tP0G6isd86ALJUeh"},{"_id":"6924ac08bf1a48f85e0ddb2d","content":{"difficulty":4,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","promises","frontend","ui","ux","devtools tech","coding","async await","async programming","coding"],"slug":"javascript-promises-complete-course---basics-to-advanced---rid---2lf744w157vmmYfDP14Q","title":"JavaScript Promises Complete Course – Basics to Advanced","resourceId":"2lf744w157vmmYfDP14Q"},{"_id":"69a52acc92f33c7d8a9f6107","content":{"difficulty":4,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ui","ux","devtools tech","tutorial","rendering","coding"],"slug":"how-react-ssr-actually-works-without-frameworks---rid---8decG2azJUycVwuG2WQE","title":"How React SSR Actually Works (Without Frameworks)","resourceId":"8decG2azJUycVwuG2WQE"}]}}