Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active May 13, 2021 10:28
Show Gist options
  • Save ross-u/773621dc771f29dfd579725a655bc1eb to your computer and use it in GitHub Desktop.
Save ross-u/773621dc771f29dfd579725a655bc1eb to your computer and use it in GitHub Desktop.
JS | Value vs Reference - 2 Rabbits and a Magic Hat

JS | Value vs Reference

This exercise is not mandatory, however it may be a good example for understanding the "variables created in functions" and concept of "passing objects (object, arrays and functions) by reference" in JavaScript.

The Riddle: 2 Rabbits and a Magic Hat 🐰 πŸ‡ 🎩


Given the below code, without running the code in the console try to answer what will be the output of 2 console.log statements on the bottom.

function magicHat(obj) {
  obj.age = 10;
  obj = { name: 'John', age: 20 };
  return obj;
}
  
let rabbit1 = { name: 'Rapha', age: 30 };
  
let rabbit2 = magicHat(rabbit1);
  
// console.log('rabbit1 ->', rabbit1); // -> ?
// console.log('rabbit2 ->', rabbit2); // -> ?

πŸš€

If you were unable to come up with the answer after some time, and/or you are not a fan of solving riddles 😁 check this link with the answer and explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment