Passed by reference javascript

Passed By Reference Vs. Value In Javascript

I think it’s important to understand memory and what goes on when you declare variables. Memory inside of a computer can be a confusing and abstract thing for a human mind to understand, so I think the best way to come to terms with it is through an analogy, which I will use as I explain this. Imagine that your computer’s memory is a warehouse. Inside of that warehouse there are storage bins where boxes of data are kept. Upon declaring a variable, you ship a box to that warehouse where it is then given a bin that will hold it, until you need it later. Primitive data types in Javascript are Passed by Value. If you’re not sure what the seven primitive data types are, that’s okay. I would stop and read this to get an idea. Chances are you’ve seen them all while you’ve been learning, but knowing the difference helps here. MDN: Javascript — Data Structures. So say you set a variable to equal another. For example:

let box1 = 'sugar' let box2 = box1 

Let’s break this down. in our proverbial warehouse one of the workers goes to the bin box1 is in, examines the box, and uses its Javascript magic to create an exact clone of it. The worker then carries the clone off and stores it in a new bin for box2 . The value is copied, you see, box1 and box2 both have ‘sugar ‘. So, what if we change one of the values?

box2 = 'brown sugar' console.log(box1) // returns 'sugar' console.log(box2) // returns 'brown sugar' 

They’re no longer the same, but that’s okay. Only the original value was passed when box2 was created, they’re not related to each other in any way and thus have no effect on each other. Objects in Javascript use Pass by Reference. Most of the constructs in Javascript we use are Objects, so I think it’s important to understand how this works. Objects constitute <> with key-value pairs, as well as things like arrays and functions. You’ve probably heard the saying that «everything in Javascript is an object.» It’s somewhat true!

const box3 =  contents: "salt" > const box4 = box3 

In this example our little worker recognizes that box3 is an Object. So he scribbles down its location in the warehouse. It then zips off to an open container for box4 and tapes the paper on the rack, referencing the location of box3 and its contents. That is Passed by Reference. Sometimes the Objects we create or pull into our apps can be massive, with hundreds or perhaps even thousands of key-value pairs. It would be incredibly wasteful and not performant of the computer to make a clone everytime. So, it simply references instead. At times this can have unforeseen consequences.

box4.contents = "pepper" console.log(box3.contents) //returns "pepper" console.log(box4.contents) //returns "pepper" 

Wait, hold on! We didn’t mean for that to happen. Why did it? Because box4 doesn’t contain its own value, it contains a reference to box3 . By updating the contains property on box4 , we’re actually telling it to update box3.contains . That right there is where the difference can come to bite us. So, the question is, how do we make a clone of box3 , rather than passing the reference along? Well, ES6 gave us a very clean and nice way to do it, the spread operator.

Mind you, this is a very basic primer to how these things work. I hope my examples and warehouse analogy helped some of you imagine the difference a little better than just reading a definition. Play around with this, experiment. Also, dig deeper, as it’s a very important subject for working with data in your apps. You’ll cross paths with it or brush up against it at some point, I guarantee it. EDIT: I found out from a really informative comment that this is a bit more nuanced than first appears, for more information check out this post: https://dev.to/xpbytes/javascript-ruby-and-c-are-not-call-by-reference-23f7

Top comments (17)

Whilst this is a great post and the overal information is correct, the pedantic semantic details are not. It all comes down to what it means to say something is «pass by x», and not what people who ask this question usually meant. I will explain why, but first

JavaScript is always pass by value

You’re not the first one that tries to make a distinction between primitives and objects, and I understand why people do. However, there is none.

The term pass by reference and pass by value only applies to function calls and their arguments. Consider the following (JS syntax) code:

function reference_assignment(myRefMaybe)  myRefMaybe =  key: 42 > > var primitiveValue= 1 var someObject=  is: 'changed?' > reference_assignment(primitiveValue) primitiveValue // => 1 reference_assignment(someObject) // => 

The fact is that someObject has not been changed, because it was not a reference to someObject ‘s content that has been passed. A language that does support pass by reference is PHP, but it requires special syntax to change from the default of passing by value:

function change_reference_value(&$actually_a_reference)  $actually_a_reference = $actually_a_reference + 1; > $value = 41; change_reference_value($value); // => $value equals 42 

I tried to keep the same sort of semantic as the JS code.

As you can see, the PHP example actually changes the value the input argument refers to.

What’s wrong with call-by-value?

The term call-by-value is problematic. In JavaScript the value that is passed is a reference. That means that, indeed, that the reference to the boxed primitive is copied, and therefore changing a primitive inside a function doesn’t affect the primitive on the outside. That also means that, indeed, the reference to a reference type, such as an array or object, is copied and passed as the value. This results in the exact behaviour that is described.

The lesser used and known term that was coined is Call by sharing which applies to Ruby, JavaScript, Python, Java and so forth. It implies that all values are object, all values are boxed, and they copy a reference when they pass it as value.

Here is another example to demonstrate this:

function appendOne(list)  list.push(1) > function replaceWithOne(list)  list = [] > const first = [] const second = [] appendOne(first) first // => [1] replaceWithOne(second) second // => [] 

In the first example it outputs [1] , because the push method modifies the object on which it is called. This propagates because the list argument still refers to the original object first (its reference was copied and passed as a value).

In the second example it outputs [] because the re-assignment doesn’t propagate to the caller. In the end it is not re-assigning the original reference but only a copy.

In short: It’s always pass by value, but the value of the variable is a reference. All primitive-methods return a new value and thus one can not modify it, all objects and arrays can have methods that modified their value, and thus one can modify it.

P.S. C actually is also always pass by value / call by value, but it allows you to pass a pointer which can simulate pass by reference:

void modifyParameters(int value, int* pointerA, int* pointerB)  // passed by value: only the local parameter is modified value = 42; // passed by value or "reference", check call site to determine which *pointerA = 42; // passed by value or "reference", check call site to determine which *pointerB = 42; > int main()  int first = 1; int second = 2; int random = 100; int* third = &random; // "first" is passed by value, which is the default // "second" is passed by reference by creating a pointer, // the pointer is passed by value, but it is followed when // using *pointerA, and thus this is like passing a reference. // "third" is passed by value. However, it's a pointer and that pointer // is followed when using *pointerB, and thus this is like // passing a reference. modifyParameters(first, &second, third); // "first" is still 1 // "second" is now 42 // "random" is now 42 // "third" is still a pointer to "random" (unchanged) return 0; > 

16 likes Like Comment button

Источник

Javascript pass by reference or value

In this article, we are going to see how javascript pass by reference or value works and the difference between the two methods.

Table of Contents

Introduction to javascript pass by reference and pass by value

Before diving into javascript pass by reference or pass by value functions, it is important to understand the difference between primitives and objects.

These are the most basic values one can think of, which includes, undefined, null, boolean, string, and numbers. Primitive values are passed by value in javascript

Whereas all objects (including functions) are passed by reference in javascript.

Let us understand what pass by reference and pass by value is before looking at examples.

Javascript pass by reference:

In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

//javascript pass by reference function callByReference(varObj) < console.log("Inside Call by Reference Method"); varObj.a = 100; console.log(varObj); >let varObj = < a: 1 >; console.log("Before Call by Reference Method"); console.log(varObj); callByReference(varObj) console.log("After Call by Reference Method"); console.log(varObj); > 

Output

Before Call by Reference Method Inside Call by Reference Method After Call by Reference Method

Javascript pass by value:

In javascript pass by value, the function is called by directly passing the value of the variable as the argument. Therefore, even changing the argument inside the function doesn’t affect the variable passed from outside the function.

It is important to note that in javascript, all function arguments are always passed by value. That is, JavaScript copies the values of the passing variables into arguments inside of the function.

//javascript pass by value function square(x) < x = x * x; return x; >var y = 10; var result = square(y); console.log(y); // 10 -- no change console.log(result); // 100 

Code Explanation

As you can see here,once we have passed the variable y to the function square, the value of y is copied to the variable x by javascript (hence pass by value).

Note that passing a functional argument by value does not have an impact on the original variable itself, as when you create a new variable (y in this case) and assign it to the value of another variable (x), another spot in memory separate from the original variable is created and a copy of (x) is placed in the new variables spot in memory. So, by value copies the value of the original variable (a) into two separate spots in memory.

On the other hand, in this case had we passed variable y by reference, then its value would have changed to 100, as in pass by reference, the function takes the original variable itself and uses it in the function rather than using a copy of the variable.

Parting Words:

On comparing both functions, namely javascript pass by reference, pass by value, we can see that ALL objects interact by reference in Javascript, so when setting equal to each other or passing to a function they all point to the same location so when you change one object you change them all. This is a stark difference compared to pass by value, wherein the pass by value function copies the value into two separate spots in memory effectively making them entirely separate entities despite one initially being set equal to the other.

Источник

Читайте также:  Тег DIV, атрибут align
Оцените статью