πŸŽ„ Get 50% off from our JavaScript course for the holidays! πŸŽ„
Does JavaScript Pass by Value or Reference?

Does JavaScript Pass by Value or Reference?

Ferenc Almasi β€’ 2020 November 12 β€’ πŸ“– 1 min read

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

const original = {};
const copy     = original;

copy.text = 'Changed the copy';

// This will output { text: β€˜Changed the copy’ }
// As `copy` references `original`
console.log(original);
value-or-reference.js
Copied to clipboard!

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:

// Using JSON.parse & JSON.stringify
JSON.parse(JSON.stringify(obj));

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

// Using object spread
{ ...obj };
deep-copy.js
Copied to clipboard!
Does JavaScript Pass by Value or Reference?
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course
50 JavaScript Interview Questions
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

πŸŽ‰ Thank you for subscribing to our newsletter. x