1

I have the following Javascript code.

var myString = 'hello world';
var myStringCopy = myString;
myString = null;

console.log(myString, myStringCopy);

the console.log output for the following is this

>null
>"hello world"

how to make sure that all the references have null value

patz
  • 1,306
  • 4
  • 25
  • 42
  • 1
    You can't really do that in JS. What is your use case? Maybe better to keep an array of values and loop through them to set to null when you are done with them. – Ryan Tuosto Apr 09 '17 at 02:31
  • Was just wondering, because we can do this for arrays and objects, why not for strings. arr.length = 0; will make all the references as [], and for objects we can use delete obj.something; which will return undefined for all the references. – patz Apr 09 '17 at 02:33
  • 3
    Strings are stored by value, whereas objects are stored by reference. – Paul Apr 09 '17 at 02:34
  • Set them both/all to null? – Mark Schultheiss Apr 09 '17 at 02:36
  • 2
    Use local variables. When the containing function ends the locals will be gone. (Unless there are closures involved, but then you don't want them gone.) *"because we can do this for arrays and objects"* - No we can't. Note that if your example had assigned an object rather than a string then you couldn't delete the object just by assigning one of the variables to `null`. – nnnnnn Apr 09 '17 at 02:38
  • @MarkSchultheiss yes, but whats the technical answer why did they not build a functionality for strings. – patz Apr 09 '17 at 02:38
  • Note that when you assign null to a string as you did here, it is no longer a string but an object with null value. A new object which is visible by `typeof myString` which returns "object" instead of the prior "string". – Mark Schultheiss Apr 09 '17 at 03:01
  • @MarkSchultheiss yes right, but converting it to other string, or number would also not take effect in the copy. but yes you are right. – patz Apr 09 '17 at 03:04
  • 2
    You can't convert a *value* to a different string or number, you can just change what value the *variable* refers to . – nnnnnn Apr 09 '17 at 03:08

1 Answers1

1

You can use a block {}, let, where variable is declared using let within block will be defined only within block

{
  let myString = 'hello world';
  let myStringCopy = myString;
  // do stuff with `myString`, `myStringCopy` here
  console.log(myString, myStringCopy);
}

try {
  console.log(myString);
} catch (e) {
  console.log(e); // `ReferenceError: myString is not defined`
}

try {
  console.log(myStringCopy);
} catch (e) {
  console.log(e); // `ReferenceError: myStringCopy is not defined`
}
guest271314
  • 1
  • 15
  • 104
  • 177