The question is how is adding an unnecessary backslash a valid key while accessing the property? And by the way it works if I remove the backslash at the key name while accessing as well.
'use strict';
let x = {
"2nu^mb$er": "number as key",
}
console.log(x["2nu\^mb$er"]); //prints: number as key
console.log(x["2nu^mb$er"]); //prints: number as key
What could be the reason behind the 2 console logs able to access the property?
The backslash
\
is used as an escape character in JavaScript. When it encounters a\
it will try to infer the special meaning of the character after it.For example
\n
means carriage return. So when the string"2nu\^mb$er"
is evaluated as the key of the object it becomes"2nu^mb$er"
, which is a valid key as\^
has no special meaning in JavaScript.So to actually have a
\
character in your string you need to escape it using another\
before it:That implies that
\
before a^
is the same as^
, as\^
in a string has no special meaning: