Access JavaScript Object Literal

Perhaps this is just a silly question, but I would appreciate the following behavior:

var obj = { key : "val1", 123 : "val2" }; obj.key; // "val1" obj.123; // Syntax error: missing; before statement obj[123]; // "val2" 

Why is obj.key different from obj.123 even though they were declared as the obj key.


Access to the object literal in this way obj.123 incorrect.

And the declaration of the object as follows is correct? The browsers I tested have IE9, firefox, and chrome, and it works great for everyone.

 var obj = { 123 : "val1" }; 
+4
source share
1 answer

JavaScript will allow you to use almost any string as the property name of an object, but when accessing properties with dot notation, you must use property names that will be valid JS identifiers that must begin with a letter, underscore, or dollar sign. Thus, for property names that do not comply with the rules for valid identifiers, you must access them using the notation for parentheses.

Although parenthesis notation works with a number, behind the scenes JS converts that number to a string.

+5
source

Source: https://habr.com/ru/post/1393322/


All Articles