Valid property names, property assignment, and JavaScript access

Updated Question

What exactly qualifies as a valid property name in Javascript? How do the different methods of appropriation of property differ? And how does a property name affect access to properties?

Note

The answers to my original question (see below) helped clarify some things, but also opened a new can of worms. Now that I had the opportunity to get a little closer acquainted with JavaScript, I believe that I was able to understand a lot.

Since it was difficult for me to find this information in one explanation, I thought it would be useful to expand my original question and try to answer it.

Original question

There was initially some confusion with the MDN JavaScript guide (object literals) . In particular, I wondered why they claimed that if the property name was not a valid JavaScript identifier, then it should be enclosed in quotation marks. However, they offered an example of code that showed that the number 7 can be used - without quotes - as the name of a property.

As it turned out, the manual just stopped one important part, and Pointy updated it (in bold):

If the property name is not a valid JavaScript identifier or number , it must be enclosed in quotation marks.

I also wondered why property names are allowed to deviate from the rule "may not start with a digit", which refers to identifiers. This question actually shows the complete misunderstanding that I had on behalf of the property, and this led me to do some more research.

+5
source share
2 answers

Short answer

Object property names can be any valid identifier , numeric literal, or string literal (including an empty string).

Based on the foregoing, there are some potentially confusing complexities that should be considered with JavaScript property names, as described below.

And if you are not working with real (non-negative integer) array indices, it would be nice to explicitly assign all the numeric property names as strings.

Negative numbers

What may look like a negative number is actually an expression - that property names do not support.

// SyntaxError const obj = { -12: 'nope' }; 

Fortunately, parenthesized notation handles expressions for us.

 // Successful property assignment. const obj = {}; obj[-12] = 'yup'; 

Typecasting

Type casting All property names are converted to strings before saving.

 const obj = { 12: '12' }; console.log(typeof Object.keys(obj)[0]); // -> string 

Syntactic

But even before the type conversion occurs, the keys are parsed according to the syntax used and converted to a decimal literal.

 const obj = { // Valid string literal '022': '022', // Interpreted as decimal 6: '6', // Interpreted as floating-point .345: '0.345', // Interpreted as floating-point 1.000: '1', // Interpreted as floating-point 8.9890: '8.989', // Interpreted as decimal 000888: '888', // Interpreted as octal 0777: '511', // Interpreted as hexadecimal 0x00111: '273', // Interpreted as binary 0b0011: '3', }; /* Quoted property name */ console.log(obj['022']); // "022"; as expected console.log(obj[022]); // undefined; 022 is an octal literal that evaluates to 18 before our lookup ever occurs /* Valid (non-negative integer) array index */ console.log(obj[6]); // "6"; as expected console.log(obj['6']); // "6"; as expected /* Non-valid array index */ console.log(obj[0x00111]); // "273"; we're accessing the property name as it was assigned (before it was parsed and typecasted) console.log(obj['0x00111']); // undefined; after parsing and typecasting, our property name seems to have disappeared console.log(obj['273']); // "273"; there it is, we found it using the evaluation of our original assignment 
+1
source

Answer to the 1st question:

Yes, the expression in the MDN manual is not 100% accurate, but in your daily work it would be better to follow it as a rule. You really don't need to create property names that are numbers.

The answer to the second question:

A property name may not start with a digit, but a property name, which is a number without any other characters in its name, is wonderful.

This exception exists because the properties with the number for the name are the same as indexes .

Let's try this:

 var obj = {7: "abc"}; obj[7]; // works fine obj.7; // gives an error (SyntaxError) 

Now try calling Array.push on the object and observe what happens:

 Array.prototype.push.call(obj, "xyz"); console.log(obj); console.log(obj[0]); // Prints Object {0: "xyz", 7: "abc", length: 1} "xyz" 

You can see that several new properties are added to the object (one with the name 0 and the other with the name length ). Alternatively, you can use the object as an array:

 var obj = { "0": "abc", "1": "xyz", length: 2 }; Array.prototype.pop.call(obj); // Returns: "xyz" Array.prototype.pop.call(obj); // Returns: "abc" 

You can use array methods for objects, and this is called Duck Typing .

Arrays are nothing more than objects with some predefined methods.

From MDN :

Array elements are object properties in the same way that length is a property, but trying to access an array element with dot notation causes a syntax error because the property name is not valid. There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a number cannot be specified using dot notation and must be accessible using notation.

Now you can understand why the number for the property name is valid. They are called simply indexes, and they are used in JavaScript arrays. And since JavaScript must match other languages, numbers are valid for index / property names.

Hope this makes it clear.

Here are some interesting articles:

+2
source

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


All Articles