Does JavaScript Pass by Value or Reference?

Does JavaScript Pass by Value or Reference?

Ferenc Almasi β€’ 2020 November 12 β€’ Read time 1 min read
  • twitter
  • facebook

JavaScript always passes by value, except when a variable refers to an object. In that case, the value is a reference to the object.

Copied to clipboard! Playground
const original = {};
const copy     = original;

copy.text = 'Changed the copy';

// This will output { text: β€˜Changed the copy’ }
// As `copy` references `original`

You can try it out with the example above. Even though you've changed copy, as the reference is pointing to original, it will be changed too. In order to do deep copy an object β€” meaning you also create a new reference to detach from the original β€” you can use one of the examples below:

Copied to clipboard! Playground
// Using JSON.parse & JSON.stringify

// Using Object.assign
Object.assign({}, obj);

// Using object spread
{ ...obj };
Does JavaScript Pass by Value or Reference?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro



This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.