0

Does the following result in a memory copy operation?

1: var foo, bar;
2: foo = 'abc';
3: bar = foo;

Is the memory representation of foo copied into the memory pointed at by bar on line 3?

Does this change if foo is a string 1 MB in size (unlike 6 bytes in this example)?

Finally, is this behavior defined by the ECMAScript specification or left to implementors?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • that is just a reference of a var, so both points to same primitive. So, IMHO there would be one primitive while two vars are having reference to it. I wish i could say it better. – Jai Apr 10 '17 at 10:38
  • But strings have pass-by-value semantics which would seem to contradict you. – Ben Aston Apr 10 '17 at 10:39
  • @BenAston Where are you observing pass-by-value semantics? JavaScript has "pass-reference-by-value" semantics for non-numeric values - also known as "call by sharing": https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing – Dai Apr 10 '17 at 10:40
  • OK, so JavaScript has "pass-reference-by-value" semantics for strings - it just doesn't expose a mechanism for changing that value because all "modifier" operations result in a new string? – Ben Aston Apr 10 '17 at 10:51

1 Answers1

2

Strings in JavaScript are immutable and can be considered as "reference types" (a-la Java and C#): Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?

I had a quick look in the ECMAScript 7 specification but I can't find a single, succinct authoritative reference that simply says "strings are immutable" - you'll have to infer that from the rest of the specification: https://www.ecma-international.org/ecma-262/7.0/index.html

Regarding the individual questions:

  1. No, the contents of the string are not copied on assignment, a reference to the string is.
  2. No, if foo pointed to a 1MB-sized string then as before, a reference would be passed.
  3. See second paragraph.
Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374