How to Force JavaScript to Deep Copy a String

Tahseen Tauseef Feb 02, 2024
  1. What Is Deep Copy
  2. How to Copy a String in JavaScript
  3. How to Deep Copy a String in JavaScript
How to Force JavaScript to Deep Copy a String

This article will discuss what a deep copy is, how to copy a string, and deep copy a string in JavaScript. We will also tackle the key difference between them.

What Is Deep Copy

In a deep copy, the whole string object is duplicated and stored in another string object. All the original string object contents are copied and stored in the new string object.

However, in copy, the original address is stored and accessed every time we access the copied string object.

How to Copy a String in JavaScript

When you copy a string, its address is stored in the specified String variable in JavaScript. Let’s look at this code segment to understand the concept better.

let original_string = 'Hello';
var string_copy = (' ' + original_string).slice(1);

In this code segment, as you can see, there was a variable named original_string, which had a string value Hello.

The original string is used as a reference after a space ' '. This concatenation results in a string copy in the browser’s implementation.

How to Deep Copy a String in JavaScript

In the mentioned explanation of the deep copy code segment, we have used a string prototype function called a slice, so let us explain the slice() prototype function first.

The slice method is used in JavaScript to retrieve a part of a string as a new string without changing the original string. Let’s see this code segment where we have used slice():

let str = 'Sliced_String';
let res = str.slice(0, 5);
console.log(res);

Output:

Slice

The first five characters from the string have been extracted and displayed on the console as an output. Note here that the arguments here are 0 indexed; hence, the 6th character is not extracted.

Alternatively, you can not provide any arguments that return the whole string as a new string.

Now, come back to the deep copy explanation.

As mentioned above, the deep copy in JavaScript duplicates the whole JavaScript string object and stores it in a specified string constant or variable. Let us look at this code segment where we have deep copied a JavaScript string object into a constant.

const str = 'I am showing an example';
const new_str = str.slice();

console.log(new_str);

In the code segment above, the program will not use the reference of the original string but will copy each character of the original string into the new string variable.

As explained above, the slice() function extracted the whole string from the str constant and returned it as a new string into the new_str constant. This new constant was shown as an output in the last line of the code segment using a console.log().

Related Article - JavaScript String