Introduction to Javascript - Objects


Can someone please explain this code ?

let spaceship = {
  homePlanet : 'Earth',
  color : 'red'
let tryReassignment = obj => {
  obj = {
    identified : false, 
    'transport type' : 'flying'
  console.log(obj) // Prints {'identified': false, 'transport type': 'flying'}

tryReassignment(spaceship) // The attempt at reassignment does not work.
spaceship // Still returns {homePlanet : 'Earth', color : 'red'};

spaceship = {
  identified : false, 
  'transport type': 'flying'
}; // Regular reassignment still works.

I didn’t understand below explanation given in the topic.

  • When we passed spaceship into that function, obj became a reference to the memory location of the spaceship object, but not to the spaceship variable. This is because the obj parameter of the tryReassignment() function is a variable in its own right. The body of tryReassignment() has no knowledge of the spaceship variable at all!

  • When we did the reassignment in the body of tryReassignment() , the obj variable came to refer to the memory location of the object {'identified' : false, 'transport type' : 'flying'} , while the spaceship variable was completely unchanged from its earlier value.


Firstly we define a spaceship object which has a homePlanet and a color value.
Then we define a tryReassignment function with one parameter called object.
Then we make the parameter (obj) to an object with two values, identified and transport type.
After this we log the parameter (obj) to the console.
Then we try the function.

Hope this helps :grinning:


Yes, I know this. I want to know why tryReassignment(spaceship) does not change the content of spaceship.


There isn’t a way to manage the actual reference values, but you only can assign some reference value to a variable.

The memory for object is allocated on its initialization

let obj = {};

after that the reference to an unnamed object (objects don’t have names, variables do) is assigned to an obj variable. After that you cannot re-allocate another object to the same place in memory.

Hope this helps :grinning:

let tryReassignment = obj => {
    obj['identified'] = false; 
    obj['transport type'] = 'flying'

Now when you pass in spaceship it will have these properties added.

If Object.assign() hasn’t come up yet, then ignore the following.

const tryReassignment = obj => {
  Object.assign(obj, {
    identified : false, 
    'transport type' : 'flying'

Now logging spaceship gives,

{ homePlanet: 'Earth',
  color: 'red',
  identified: false,
  'transport type': 'flying' }