1

The answer might be obvious but I didn't find out. I have this code :

const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
console.log(arr); // prints ["Hello"]

I just want to copy the string reference so when I change the currentStr value, it also change its reference in the array (here the first item of the arr array).

const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
console.log(arr); // expect print ["Hello world"]

7
  • you are not pushing into the array - you are just joint two strings together - hence why the print [Hello] from the original arr Commented Sep 1, 2020 at 10:46
  • arr[0] += " world" did you try like this or you want entirely different things,? Commented Sep 1, 2020 at 10:47
  • @Always No I just want to concat the first item, not pushing into the array Commented Sep 1, 2020 at 10:48
  • @MuratÇimen No I just want to concat to the reference Commented Sep 1, 2020 at 10:49
  • 3
    string is immutable. When you change it, its reference changes. Commented Sep 1, 2020 at 10:53

3 Answers 3

1

In Javascript strings are immutable. I.e. when you make a change to a string behind the scenes Javascript is making a new copy of that string. Arrays are slightly different. You can mutate arrays. I.e. change what they are storing.

To achieve what you want you can use the splice method on the array to replace the 'Hello' string with a new string called 'Hello' + ' World'. Here is the code for it.

const arr = ['Hello']
arr.splice(0,1, arr[0] + ' World') 
console.log(arr) // ['Hello World']

See the MDN docs on Arrays, and the splice method.

Sign up to request clarification or add additional context in comments.

Comments

0
const arr = ["Hello"];
var currentStr=[];
let newStr= arr[0]+" World"; 
currentStr.push(newStr)
console.log(currentStr); //
console.log(arr); //

1 Comment

Leaving it open but please add an explanatory line.
0

You can do this by re-assigning currentStr to arr[0].

const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
arr[0] = currentStr;
console.log(arr); // prints ["Hello world"]

Comments

Your Answer

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