Javascript colon mess

I am learning javascript myself. There is confusion with some javascript,

price = 14; name = "Mary"; apples:5; //This line executing without error "orranges":6; //This line getting error alert(name); 

Both of these lines can be used in a json object without any errors. But when I use these lines outside the json object, the second line appears ( "orranges": 6; ). Why is this? And why doesn't it give an error for the first line ( Apples: 5; ), is there a way I can use it outside of the json object?

+5
source share
1 answer

: not an operator; it is part of the shortcut syntax.

See MDN

label :
statement

label - Any JavaScript identifier that is not a reserved word.

apples is an identifier.

"orranges" is a string literal.

Is there a way I can use it outside of a json object?

It seems you are mixing JSON with the object literal syntax.

You cannot use : as a character that separates a property name from a value in an object when you are not in the process of defining an object.

+8
source

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


All Articles