Member-only story

Strings are not copied in JavaScript

What is really stored inside variables in JavaScript?

Marian C.
4 min readSep 8, 2021
The illustration borrowed from https://www.html5rocks.com/en/tutorials/memory/effectivemanagement/

Objects

Everyone knows that when an object is assigned to a variable, the object value is saved somewhere in memory and the target variable is assigned the reference to the object location in memory. If the reference is assigned to another variable and then any of the two variables can be used to modify the same object:

// sample1.js
let a={id:1};
let b=a;
b.id=2;
console.log(a); // {id: 2}

Non-objects

The JavaScript data types can divided into two groups: objects and primitive types.

Objects are collections of properties. Properties is the fancy term for variables grouped inside an object. The fundamental difference between objects and primitive types is that the primitive types cannot have properties. For example, if I try to assign a property to a string, I receive an explicit error:

// sample2.js
let str='a';
str.id=1; // TypeError: Cannot create property 'id' on string 'a'

Strings

String is a particularly interesting subject because in practically any web application strings, or in other words contents, take most of the allocated memory.

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

Responses (1)