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?

4
  • 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. Commented Apr 10, 2017 at 10:38
  • But strings have pass-by-value semantics which would seem to contradict you. Commented Apr 10, 2017 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": en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing Commented Apr 10, 2017 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? Commented Apr 10, 2017 at 10:51

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.