Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript spread syntax vs jQuery $.extend - ByRef and ByVal

I am trying to update an object that is deeply nested and thus has a rather long name that I do not want to keep typing in my code. In this discussion, I shall call it by the shorter name 'target'.

I begin by referring to it by the shorter name 'c':

c = target

I then want to update its contents using another object; call it update.

If I use c = $.extend(c,update), the reference to c remains 'intact'; i.e. c === target is true.

However, if I use c = {...c, ...update}, a new variable is created; i.e. c === target is false. My original target variable is not updated.

I do not understand why. Can anyone explain?

There is a bin at $extends vs JavaScript spread

like image 716
jladbury Avatar asked Nov 15 '25 14:11

jladbury


1 Answers

The jQuery docs are pretty clear about how extend() works:

the target object (first argument) will be modified, and will also be returned from $.extend()

Using the spread operator is different. When you write this:

c = {...c, ...update}

you are creating a new object. You then assign c to point at that new object. The object that c previously pointed to has nothing to do with any of this. It simply (from: tc29/proposal):

copies own enumerable properties from a provided object onto the newly created object

To get the behavior you want you can use Object.assign();

let target = {
  name: "Mark",
  place: "AK"
}

let c = target;

Object.assign(c, {
  name: "Tim"
})
console.log(target)
like image 108
Mark Avatar answered Nov 18 '25 21:11

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!