Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty a String in JS

Tags:

javascript

How to empty a string in JS keeping the same object reference ?

var str= "hello";
str=""; // this will clear the string but will create a new reference 
like image 377
Mok Avatar asked Sep 19 '25 09:09

Mok


1 Answers

Strings are immutable (unchangable) so you can't do this. All operations that "modify" a string actually create a new/different string so the reference will be different.


Your type of problem is usually solved by having a string reference contained in an object. You pass the reference to the containing object and then you can change the string, but still have a reference to the new string.

var container = {
    myStr: "hello";
};

container.myStr = "";

myFunc(container);

// myFunc could have modified container.myStr and the new value would be here
console.log(container.myStr)

This allows code, both before, during and after the myFunc() function call to change container.myStr and have that object always contain a reference to the latest value of the string.

like image 117
jfriend00 Avatar answered Sep 20 '25 22:09

jfriend00