0

I am a newbie in Javascript. Recently, while using React for a project, I couldn't make my program work as I wanted it to until a friend of mine pointed out that all variable assignments in Javascript are by reference to increase performance. So I cloned most of my variables instead and now it worked.

But this defeats the purpose of this Javascript quirk which is to increase speed. So I figured that I only needed to clone the states that I will perform calculations to so that I can reuse the state's original values later.

Besides this, are there any hard and fast rules about when I should/should not clone variables in Javascript?

  • Probably, either when it's needed for the script to run properly, or when you just want to create a new object based on an old one while avoiding mutation (like one would do in functional programming) – CertainPerformance Jul 27 '19 at 09:58
  • 1
    "*all variable assignments in Javascript are by reference*" That is only true for objects, not for primitive types. – str Jul 27 '19 at 09:59
  • [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Andreas Jul 27 '19 at 10:15
  • @str—I like this from Andreas' link: "*[some] may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself.*" ;-) – RobG Jul 27 '19 at 11:26

0 Answers0