Advertisement
makispaiktis

Objects - Do they change with updating and reassigning them into a function?

Oct 19th, 2024
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 1a. UPDATE/ADD key-value pairs
  2. function greenEnergy(obj){
  3.     obj['Fuel Type'] = 'avocado oil';
  4. }
  5. function remotelyDisable(obj){
  6.     obj.disabled = true;
  7. }
  8. // 1b. REASSIGN the whole object
  9. function reassign(obj){
  10.     obj = {changed:true, name:'NEW OBJECT'};
  11. }
  12. // 1c. REASSIGN the whole object and RETURN
  13. function reassign_and_return(obj){
  14.     obj = {changed:true, name:'NEW OBJECT'};
  15.     return obj;
  16. }
  17.  
  18.  
  19. // MAIN FUNCTION
  20. let spaceship = {'Fuel Type' : 'Turbo Fuel', homePlanet : 'Earth'};
  21.  
  22. console.log('1) Updating/adding key-value pairs !! CHANGES !! the object');
  23. greenEnergy(spaceship);
  24. console.log(spaceship);
  25. remotelyDisable(spaceship);
  26. console.log(spaceship);
  27.  
  28. console.log('\n2) Reassigning the object (without returning it) !! DOES NOT !! change the object');
  29. reassign(spaceship);
  30. console.log(spaceship);
  31.  
  32. console.log('\n3) Reassigning the object and returning it !! CHANGES !! the object');
  33. spaceship = reassign_and_return(spaceship);
  34. console.log(spaceship);
  35.  
  36.  
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement