{"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":11162,"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":"673f3c88d34d7f4b8ccfbfaf","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","frontend","html","css","ui","ux","virtual dom","dom elements","trees","rendering","ui rendering","dom tree"],"slug":"build-a-virtual-dom-to-actual-html-dom-convertor-or-dom-renderer---qid---bAin2TEn862JTFVFgxEi","title":"Build a Virtual DOM to actual HTML DOM Convertor | DOM Renderer","questionId":"bAin2TEn862JTFVFgxEi"},{"_id":"6871628350393ab55076954e","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","problem solving","frontend","coding interview","ui","ux","uber frontend interview","devtools tech","tech tutorial","frontend coding challenge"],"slug":"company-structure-validator---qid---UhGdKfJaM4a7VuQsFRV3","title":"Company Structure Validator","questionId":"UhGdKfJaM4a7VuQsFRV3"},{"_id":"5f0ad08e3cce8c36cd29253d","content":{"difficulty":1,"languages":"html"},"tags":["frontend fundamentals","defer vs async","javascript","web","code","script tag","critical rendering path"],"slug":"difference-between-defer-and-async-keywords---qid---RtkQBI3Pbny5DhYLilhS","title":"Difference between Defer and Async keywords?","questionId":"RtkQBI3Pbny5DhYLilhS"},{"_id":"69e9eb04f93997aa6f62181b","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["javascript","ui","ux","devtools tech","coding","frontend","ui challenge"],"slug":"async-fetcher-with-error-handling---qid---ACHwKMlra3csxMbCHnfy","title":"Async Fetcher with Error Handling","questionId":"ACHwKMlra3csxMbCHnfy"},{"_id":"64f86accd5ab2876a4c49e4c","content":{"languages":["react","html"],"difficulty":3},"tags":["","javascript","react","frontend","code","devtools tech","tutorial","frontend interview questions","youtube","gojek","gif","giphy","gif search","web app","interview question","frontend coding challenge"],"slug":"build-a-gif-search-engine-or-frontend-coding-challenge-or-react-js-or-javascript---qid---Yrz7qTiDTIyReYmwrLiA","title":"Build a GIF Search Engine | Frontend Coding Challenge | React.js | JavaScript","questionId":"Yrz7qTiDTIyReYmwrLiA"}],"resources":[{"_id":"697b25a8132ce4e954d59b37","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":[""],"slug":"rippling-frontend-interview-experience---rid---n4yp5bZBiParUibIGjEe","title":"Rippling Frontend Interview Experience","resourceId":"n4yp5bZBiParUibIGjEe"},{"_id":"69234db2bf1a48f85e0d254f","content":{"difficulty":1,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ui","ux","csr","ssr","rendering","frontend system design"],"slug":"mastering-rendering-techniques-csr-ssr-streaming-with-selective-hydration---rid---Gw29cwskE3GjZbvpAcql","title":"Mastering Rendering Techniques: CSR, SSR, Streaming with Selective Hydration","resourceId":"Gw29cwskE3GjZbvpAcql"},{"_id":"698de48a3354c04596030105","content":{"difficulty":4,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","frontend","ui","ux","faang","interview experiences","coding"],"slug":"why-people-fail-at-interviews---rid---bQAGNih8yTqlrgq1O04x","title":"Why people fail at interviews?","resourceId":"bQAGNih8yTqlrgq1O04x"},{"_id":"690cd2dee48888ea5a7e7ba5","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","amazon","frontend","interview experience","ui","ux","tutorial","blog"],"slug":"amazon-frontend-engineer-interview-experience-and-tips---rid---A41fCaZ2TeZcvjo6ua5p","title":"Amazon Frontend Engineer Interview Experience & Tips","resourceId":"A41fCaZ2TeZcvjo6ua5p"},{"_id":"5fc7215a6d3cda64e470c415","content":{"difficulty":4,"domain":1,"type":5},"tags":["linkedin","jobs","skills","career","indemand","devtools"],"slug":"move-close-to-your-dream-job-find-out-top-skills-in-the-market---rid---layhD7GHUKsulhIM25yM","title":"Move close to your dream job. Find out top skills in the market.","resourceId":"layhD7GHUKsulhIM25yM"}]}}