Why does accessing a property work even if I include an unnecessary backslash while accessing?

55 views Asked by At

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?

2

There are 2 answers

0
Fullstack Guy On

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:

'use strict';
let x  = {
  "2nu^mb$er": "number as key",
}
//prints: undefined as now the key becomes 2nu\^mb$er
console.log(x["2nu\\^mb$er"]);
 //prints: number as key as the key is 2nu^mb$er
console.log(x["2nu\^mb$er"]); 

That implies that \ before a ^ is the same as ^, as \^ in a string has no special meaning:

console.log("\^" == "^")

4
Andres Gardiol On

This is why, from this docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

An object property name can be any valid JavaScript string, or anything that can be converted to a string...

Please note that all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols

This means that "2nu\^mb$er" is converted to a string. So that's why accessing to an object property name works even with that back slash

For example:

let a = "abc\d";
console.log(a);