I'm wondering why the console.log returns backslashes in this simple example that I followed on a tutorial (I'm quite new to using localStorage) -
localStorage.clear();
let myObj = { name: "Bob", age: 50 };
let myObj_serialized = JSON.stringify(myObj);
localStorage.setItem("myObj", myObj_serialized);
console.log(localStorage);
I've seen other posts where it explains how you can remove the backslashes, however, I wanted to know why this happens and how I can avoid this.
The link of the tutorial I followed was - https://www.youtube.com/watch?v=AUOzvFzdIk4&t=275s
Thanks.
The reason this happens is the stringified object uses JSON, proper JSON has " surrounding properties and (string) values. However - the thing you're saving is also a string. In order for this to store properly, it must escape the inner ".
For instance, if you were to manually create the same stringified JSON, you would need to do the same, otherwise you would be constantly opening and closing your string definition:
// suggested and invalid.
let stringThing = "{"name":"Bob","age":50}";
// correct
let stringThing2 = "{\"name\":\"Bob\",\"age\":50}";
Now obviously there are ways around this in js, can simply use ' to start the string, and you no longer need to escape the ", but you would still see escape double quotes if you were to log out the resulting string.
EDIT
evolutionxbox made an excellent point in the comments on this answer - but it needs a little clarification. the \ is an escape character (in javascript). When used on its own in a string it will never actually show if you were to print the value of that string to the screen on the DOM.
The \ showing in your saved data is technically not actually there in the string when in memory. It is placed there when storing, so that when parsed back into a string later on it doesn't terminate the string early (like in my stringThing variable).
The most common use I've seen for \ in strings is on string terminating characters. In this case ". Escaping " characters was created so that people and computers could determine if the character existed inside the string or not.
NOTE if you were to console.log your myObj_serialized variable, you'd see that the output does not show \". This supports the point of the \ not actually existing in the string when in memory.
This is a mild oversimplification of the purpose and use of escaped characters - but you can rest assured, removing the \ from your stored objects would be a mistake, and when you parse that value back into memory, you won't even know they were there in the first place.