Javascript object property quotes [duplicate] - javascript

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
Let's say I have the following object:
var VariableName = {
firstProperty: 1,
secondProperty: 2
}
Do I have to wrap the object properties in quotes like this?
var VariableName = {
'firstProperty': 1,
'secondProperty': 2
}
Is this Single quotes in JavaScript object literal the correct answer?

No, you don't need to do that.
The only reasons to quote object-keys are
the property name is reserved/used by the browser/js engine (eg. "class" in IE)
you have special characters or white spaces in your key
so for instance
var VariableName = {
"some-prop": 42, // needs quotation because of `-`
"class": 'foobar' // doesn't syntatically require quotes, but it will fail on some IEs
valid: 'yay' // no quotes required
};

You only have to use the quotes around the property, if the property name is a reserved word (like for, in, function, ...). That way you prevent Javascript from trying to interpret the keyword as a part of the language and most probably get a syntax error.
Furthermore, if you want to use spaces in property names, you also have to use quotes.
If your property names are just normal names without any collusion potential or spaces, you may use the syntax you prefer.
One other possibility that requires quotes is the use of Javascript minifiers like google closure compiler, as it tends to replace all property names. If you put your property names in quotes, however, the closure compiler preserves the property as you coded it. This has some relevance when exporting objects in a library or using an parameter object.

Property names in object literals must be strings, numbers or identifiers. If the name is a valid identifier, then you don't need quotes, otherwise they follow the same rules as strings.
firstProperty and secondProperty are both valid identifiers, so you don't need quotes.
See page 65 of the specification for more details.

For Javascript you usually do not have to use quotes. You may use ' or " if you like, and you must use quotes if there is a clash between the name of your property and a JS reserved word like null. The answer you linked to seems to be correct, yes.
For JSON, you should use " around strings (including object property names)

Related

Is there any ways to make this code shorter to return object? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 5 years ago.
What is the real difference in using [] and . for accessing array or object properties? Which one to use?
Also why doesn't . operator allow the index property?
Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.
The dot notation only works with property names which are valid identifier names [spec], so basically any name that would also be a valid variable name (a valid identifier, see also What characters are valid for JavaScript variable names?) and any reserved keyword [spec].
Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.
Examples:
obj.foo; // valid
obj.else // valid, reserved keywords are valid identifier names
obj.42 // invalid, identifier names cannot start with numbers
obj.3foo // invalid, ""
obj.foo-bar // invalid, `-` is not allowed in identifier names
obj[42] // valid, 42 will be coerced to "42"
obj["--"] // valid, any character sequence is allowed
obj[bar] // valid, will evaluate the variable `bar` and
// use its value as property name
Use bracket notation:
When the property name is contained in a variable, e.g. obj[foo].
The property name contains characters not permitted in identifiers, e.g. starts with a digit†, or contains a space or dash (-), e.g. obj["my property"].
Use dot notation: In all other situations.
There is a caveat though regarding reserved keywords. While the specification permits to use them as property names and with the dot notation, not all browsers or tools respect this (notably older IE versions). So the best solution in my opinion is to avoid using reserved keywords for property names or use bracket notation if you cannot.
†: That's also the reason why you can only use bracket notation to access array elements. Identifiers cannot start with digits, and hence cannot consist only of digits.
You should use . when you know the name of the property
var object = {};
object.property = 'whatever';
, use [] when the name of the property is contained in a variable
var object = {};
var property = 'another-property';
object[property] = 'whatever';
As #DCoder added certain object properties cannot be accessed without using the [] notation because their names break the syntax. E.g. properties named class, default, or data-prop-value
Also why doesn't . operator allow the index property? I really want
full reason. Thank you.
Well if that was possible, consider:
var a = 0.5;
Did you mean the number 0.5 or access the 5 element of the number?
See:
Number.prototype[5] = 3;
0[5] //3
0.5 // 0.5
If you allowed the syntax 0.5 to be equal to 0[5], then how do you know what you mean?
It is however possible to use numbers directly with object literal:
var a = {
0: 3,
1: 5
};
Both dot operator and index(bracket notation) operator are used to access the property of an Object. Generally accessing with dot operator is quite faster because accessing variables by window is significantly slower though. But in case of special character
in the variables, you cannot use dot operator as it will give error. For such cases we need to use index operator and pass the variable name as a string format means underdouble quote otherwise it will give undefined error.
e.g-
var abc = {
font-size : "12px"
}
Using dot operator - abc.font-size; //it will give error (Incorrect)
Using index operator - abc["font-size"]; //12px (Correct)

Javascript Object attribute with '-' doesn't work properly [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 7 years ago.
I have a JSON response in the following format.
{
"_meta" : {
"next-person-id" : "1001",
"totalPersons" : "1000"
}
}
I am using Angular's $http service to retrieve this and trying to access next-person-id attribute in javascript like the following,
$http.get(url).then(
function(response){
console.log(response._meta.next-person-id);
}
);
But the next-person-id in the response is undefined always. But I'm able to access totalPersons attribute. Is there any problem with getting attributes with '-' character in javascript?
Use bracket notation:
console.log(response._meta['next-person-id']);
A possible alternative is to change the keys to use underscores, so that _meta.next_person_id would work.
You cant write variables using - as it is also a minus sign.
To solve this, use square bracket notation:
console.log(response._meta['next-person-id']);
Yep true, because in JavaScript you can use Latin letters, numbers and $ _ symbols for variables or properties.
If you want to use -, you should escape it with string quotes.
like this
var obj = {
'next-person-id': 2
}
console.log(obj['next-person-id']); // 2
Explanation:
In Global scope - means minus. It tries to subtract person from name. So you will get an error like this:
ReferenceError: name is not defined
In JS you can access to object property in 2 ways
1) Dot nation
obj.property
2) Square bracket nation
obj['property']
Here you need to parse string, so as you know in string you can have any symbols except string quote symbol (it will close the string)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation

using chinese as the key of object [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
How can I use a Chinese character or a number as the key of an object like this:
var obj = { 我: 'me', 20: 'you' };
console.log(obj.我); // me
console.log(obj[我]); // -> Reference Error: 我 is not defined
console.log(obj[20]); // you
console.log(obj.20); // ->Syntax Error: Unexpected number
In order to use dot notation in object, key must be a valid JavaScript identifier. Mozilla Documentation Network states:
You can use ISO 8859-1 or Unicode letters such as å and ü in
identifiers. You can also use the Unicode escape sequences as
characters in identifiers.
And indeed, in Firefox this is valid syntax:
var x = { 我: 5 };
x.我
var 我 = 42;
console.log(我);
Chrome accepts this too.
In case your browser (or browser your visitors use) do not follow standards that closely, you can use:
var obj = { '我': 'me', 20: 'you' };
console.log(obj['我']);
It's worth noting that you can use arbitrary strings as object keys, even if they are not valid JavaScript identifiers (eg. thay contain spaces and/or punctuation):
var obj = { " ": "space", ";": "semicolon" };
It's generally a bad practice to include non ANSI characters in your source JS code in .html* or .js files, as they may be lost during editing the files (i.e. while saving as ANSI instead of Unicode format) or when switching the hosting OS.
Consider converting these characters to their Unicode equivalent using JavaScript's escape() method for instance (i.e. escape('我') returns: "%u6211").
Check the following link for complete info:
W3C character escapes in markup and CSS
Your confusion is that obj.我 works but obj[我] doesn't? On the other hand, obj[20] does?
Well, 20 is a value literal. You can write 20 anywhere to create the number value 20. On the other hand, 我 is not a valid literal for anything. If you want to create the string value "我", you need to write '我'. On the other hand, if you want 我 to be a variable name, you need to declare the variable beforehand with var 我. The error you're seeing is telling you that there's no variable 我 defined.
On the other hand again, obj.20 is invalid syntax since 20 is not a valid variable name. The reason for that is that numeric literals create numbers, hence the syntax would become ambiguous if they could also be used as variable names. Does foo = 20 mean you want to assign the number 20 to foo, or the value of the variable 20? Hence, numeric literals are reserved for numbers, period.
obj.我 → requires valid symbol name, 我 is valid symbol name
obj[我] → requires valid *value*, 我 is not value literal nor declared variable
obj.20 → requires valid symbol name, 20 is not valid symbol name
obj[20] → requires valid *value*, 20 is valid value literal
This would work just fine:
var 我 = '我';
obj[我];

In JavaScript, what is the difference between a property name in double-quotes ("") and without? [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
What's the difference between car.manyCars.a and car.manyCars.b in this example?
None whatsoever.
Quotes allow you to specify names which are not valid javascript identifiers, but both a and b are. For example, this wouldn't be legal:
var car = { a*b: "Saab" };
whereas this would be
var car = { "a*b": "Saab" };
As a*b is not a valid identifier.
Note that JSON (which is based on JavaScript) does not allow unquoted names.
Edit
An exception here, as you've noticed, you can use numbers without quoting them, which are not valid javascript identifiers. This is actually rather weird, don't have a good reason for this, probably the opportunity to shorthand the declaration. car.7 won't parse for the same reason, it is not a valid identifier, and you need to use car[7].
As roe said, there's no difference in the end, but it allows to you to use otherwise reserved keywords or invalid identifiers:
var x = { 'a b c' : 1, 'a%#!6!#' : 1};
It probably isn't a bad idea to always use quotes. Different javascript engines consider different things to be reserved. For example, this works fine in a browser, but causes a syntax error in Rhino:
var x = { native : true };
The Mozilla Developer Network has some good information too: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators
Dot notation
some_object.property
property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.
Bracket notation
some_object[property]
property is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

Why are some object-literal properties quoted and others not? [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 9 years ago.
I see this all the time: object literals declared such that some keys are surrounded with quotes and others are not. An example from jQuery 1.4.2:
jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
What is the significance of wrapping the first two property keys (for and class) with quotes, while leaving the others quote-less? Are there any differences at all?
I've been poking around the ECMAScript 5 specification; all I've been able to find is [Note 6 of Section 15.12.3, emphasis mine]:
NOTE 6 An object is rendered as an
opening left brace followed by zero or
more properties, separated with
commas, closed with a right brace. A
property is a quoted String
representing the key or property name,
a colon, and then the stringified
property value. An array is rendered
as an opening left bracket followed by
zero or more values, separated with
commas, closed with a right bracket.
However, this refers only to the stringification of JSON.
Those are Javascript reserved words, and (though not really necessary) the syntax of the language requires that they be quoted.
Strictly speaking, pure "JSON" notation requires that all of the "key" strings be quoted. Javascript itself however is OK with keys that are valid identifiers (but not reserved words) being unquoted.
There is a reason at this point (two plus years later) to quote object literal properties. If one wants to minify their code using the Closure Compiler they may need to make the properties accessible to other source files. In that case, they will want to avoid having symbols renamed by the compiler. By quoting the property name, the Closure Compiler will not minify (rename) them.
See: Removal of code you want to keep
(This applies to at least the ADVANCED_OPTIMIZATIONS setting.)
Javascript language keywords or reserved keywords are always surrounded by quotes in there.
for and class are language keywords. Your interpreter would throw a SyntaxError when those are unquoted.
See section 7.6.1.1 in the Spec you linked to.
Javascript has a lot of reserved words that are not actually used by the language which I think were reserved for possible future use. class is one of these even though Javascript does not actually use classes. Another is goto and there's absolutely no chance of that ever being used. The result, however, is that if you want to use these as a json key then it has to be quoted. Strictly speaking you should probably always quote your keys just to avoid the possibility of falling foul of the javascript unused reserved word trap (mind you - I never do).

Categories

Resources