4

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 
0

1 Answer 1

9

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.

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.