Question about Built-in Object Methods (Object.assign)

Hello Everyone,

I was doing the JS course, and I was going through the “Built-in Object Methods (ADVANCED OBJECTS)” exercise when I was creating step 3. The Object.assign().

Build-in Object Methods Advanced

I created the following code:

const robot = { model: 'SAL-1000', mobile: true, sentient: false, armor: 'Steel-plated', energyLevel: 75 }; const newRobot = Object.assign(robot, { laserBlaster: true, voiceRecognition: true }) console.log(newRobot);

This was, according to the exercise, wrong. I was wondering why, so I took a look at the error message which said:

Did you provide the correct second argument? The robot object should not be changed

Mhm… alright. I took a look at the solution, there it said the following:

const robot = { model: 'SAL-1000', mobile: true, sentient: false, armor: 'Steel-plated', energyLevel: 75 }; const newRobot = Object.assign({ laserBlaster: true, voiceRecognition: true }, robot); //added console.log to make it runnable console.log(robot)

So, first the new code, then the object you want to assign the code to. This seemed inlogical to me. So next I took a look at the MDN’s Syntax section:

MDN’s syntax section

There it explains the first argument is the target, the second is the source.

Isnt it so that the robot object is the target which you want to add the code to, and the code is the source? Thus making robot the first argument, and the code the second? Or am I getting something wrong here?

Hi there!

I was also pretty confused on this part, but what I did which helped me out a lot is first I declared a new robot object with the following:

const newRobotExtra = {laserBlaster: true, voiceRecognition: true}

and from there I declared the new robot variable
const newRobot = Object.assign(newRobotExtra, robot) which adds {laserBlaster: true, voiceRecognition: true} to my new variable.

Object.assign(target = newRobot, source = robot);

It may not be the correct way but it helped me map it out a bit better and it added all the robot properties without changing the const robot obj declared in the first line.