How to pass a compound value by value copy (YDKJS types and grammar)

How to pass a compound value by value copy (YDKJS types and grammar)
0

#1

Remember: you cannot directly control/override value-copy vs. reference – those semantics are controlled entirely by the type of the underlying value.

To effectively pass a compound value (like an array) by value-copy, you need to manually make a copy of it, so that the reference passed doesn’t still point to the original. For example:

foo( a.slice() );

slice(…) with no parameters by default makes an entirely new (shallow) copy of the array. So, we pass in a reference only to the copied array, and thus foo(…) cannot affect the contents of a.

To do the reverse – pass a scalar primitive value in a way where its value updates can be seen, kinda like a reference – you have to wrap the value in another compound value (object, array, etc) that can be passed by reference-copy:

function foo(wrapper) {
	wrapper.a = 42;
}

var obj = {
	a: 2
};

foo( obj );

obj.a; // 42

Can someone explain the above paragraphs in a more direct way? I don’t quite understand what the author is trying to do.


#2

Before the part you quoted, he explained that:

  • for simple data (numbers, strings, etc…), values are copied when you assign them to a variable or pass them to function
  • for compound data (arrays, objects), values are passed by reference. If you assign an object to several variables, you have only one object in memory and several variables keeping track of it, so that it you manipulate it with one variable, it will affect the other variables.

Here he shows what you need to do if you want to invert that behaviour:

  • how to copy an array so you can manipulate the copy without affecting the original array
  • how to pass a simple data value by reference so you can change its value with an assignment in a function and still affect the original value.

Granted, the second case is a bit convoluted because we’re now manipulating an object instead of a simple data value, but I think it’s just to show what’s possible.


#3

thank you so much. maybe it is my english is not good enough or sometimes the author say things in a more indirect way… I think he sometimes tries too hard to use a lot of big words in his book. Or he is simply just trying to be more precise.

but anyway. thanks for the clarification.

:wink: