JS Objects: Pass by Reference or Value?

Is JS pass by value or reference ? What we generally think ? Primitives are passed by value; objects are passed by reference. The most shared example to validate this claim is const changeObj = (obj) => { obj.key1 = "value2"; console.log(obj.key1); // value2 }; const obj = { key1: "value1" }; console.log(obj.key1); // value1 changeObj(obj); console.log(obj.key1); // value2 Asking: what is pass by reference ? True References are Aliases. They actually share the same address. If you know a bit of C++, then you can understand this easily. #include <iostream> void swap(int& a, int& b) { int temp = a; a = b; b = temp; } int main() { int x = 5; int y = 6; // The values of x and y actually swap here. x = 6, y = 5 swap(x, y); } What javascript object references are ? JS object references are pointers. The variable points to object in memory. But if you try to reassign that variable inside a function to point to a completely new object? The original variable doesn't care. It still points to the original object. You can modify properties through the reference ✅ But you can't reassign the original variable ❌ Sources: 1. https://lnkd.in/gE7Zasm3 2. https://lnkd.in/ghvff7ED #javascript #til

To view or add a comment, sign in

Explore content categories