Maybe is just a stupid question, but,
I would appreciate having an explanation of the following behavior:
var obj = {
key : "val1",
123 : "val2"
};
obj.key; // "val1"
obj.123; // Syntax error: missing; before statement
obj[123]; // "val2"
Why obj.key is different from obj.123
although they have been declared both as keys of obj.
Accessing the object literal in this way obj.123 is wrong.
And declaring the object in the following way is correct?
The browsers I have tested are IE9, firefox and chrome and for all of them it works fine.
var obj = {
123 : "val1"
};
JavaScript will let you use just about any string as an object property name, but when accessing properties with the dot notation you're only supposed to use property names that would be valid JS identifiers - which have to start with a letter, the underscore or a dollar sign. So for property names that don't meet the rules for valid identifiers you have to access them with the bracket notation.
Although the bracket notation works with a number, behind the scenes JS will convert that number to a string.
Related
This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 4 years ago.
I am a JavaScript learner and want to know what is the difference between
var obj1 = {
attribute1 : 1
};
var obj2 = {
"attribute1" : 1
};
console.log(obj1.attribute1);
console.log(obj2.attribute1);
Both of them prints 1. Is there a major difference among them?
They are equivalent in your case.
Internally, they are the same.
What could change is the way you can access them with your code.
When using strings (quoted properties), you can actually use more exotic names for your properties :
var obj3 = {
"attribute with space": 1,
"123AttributeStartingWithANumber": 1,
}
In my example, you cannot access those attribute names via the obj1.attributeName syntax (but you can with the brackets notations : obj1["attribute with space"] or obj1["123AttributeStartingWithANumber"] .
This is because "attribute with space" or "123Attribute" are not valid identifiers in JS.
Note that in your example you can also use the bracket notation :
console.log(obj1["attribute1"]);
console.log(obj2["attribute1"]);
In summary, to quote deceze's comment :
Quoted properties and bracket notation always work, unquoted
properties and . dot access is shorthand for when your property name
is a valid identifier.
There is no difference.
Object literal syntax allows you to use a string or an identifier to provide the property name.
A string allows you to use characters (such as or .) which are not allowed in an identifier, but attribute1 has none of those characters in it.
You can make object keys with space in them if you declare them as strings:
var obj1 = {
attribute1 : 1 // but you cannot say my attribute1: 1 it will throw syntax error
};
var obj2 = {
"my attribute1" : 1
};
console.log(obj1.attribute1);
console.log(obj2.attribute1);
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed last year.
What is difference between below:
var ourDog = {
"name": "Camper"
};
and
var ourDog = {
name: "Camper",
};
And how it is able to return Camper for ourDog["name"] in both cases.
Is there any conversion happening behind the scene, when we access object properties with [] notation?
Check the specs
PropertyDefinition : PropertyName : AssignmentExpression
Return PropName of PropertyName.
This part of spec suggests the formal syntax of the property name with its value.
Also, before that this part of the spec suggest that propertyName could be literalPropertyName which need not be described as a string.
PropertyName[Yield] :
LiteralPropertyName
ComputedPropertyName[?Yield]
LiteralPropertyName :
IdentifierName
StringLiteral
NumericLiteral
This is why you will get same result for both name and "name".
However, if the property name is first name, then you need to use the string otherwise you will get a compilation error since after the property name a colon : is expected.
//correct syntax
var ourDog = {
"first name": "Camper"
};
//incorrect syntax
var ourDog = {
first name: "Camper" //since after first there is no colon so there will be compilation error
};
http://ecma-international.org/ecma-262/6.0/#sec-object-initializer
A property name can only be an identifier name (i.e. identifiers + reserved words), a string literal, or a numeric literal.
you cant use a numeric literal with dot notation but bracket notation works:
var ourDog = {
123: "Camper",
};
Output
ourDog[123] // Camper
but
ourDog.123 // SyntaxError
for more information take a look into this
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method
var object = {};
object['1'] = 'value';
console.log(object[1]);
This outputs "value", since 1 is type-casted into '1'.
Example is from MDN
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I have this JSON code :
{
"query": {
"pages": {
"-1": {
"ns": 0,
"title": "StackOverflow",
}
}
}
}
I parsed it into a JSON object :
data = JSON.parse(jsonString);
Why to access the object -1 I must do data.query.pages[-1] not data.query.pages.-1. In this example pages is not an array but an object.
It's not an array, it's an object. Both object["name"] and object.name are identical ways of accessing a property called name on the given object.
You cannot access an object property with object.-1, simply because that's a syntax error, the same way you can't use object.+1 or object.[1 or object./1. They're all valid names for a property of an object, but they're syntactically invalid when using object.propertyName syntax.
The other caveat is that you cannot have property names which are integers. Setting or getting object[-1] is identical to object["-1"] as the property name is converted to a string. It would be identical to accessing object.-1 if that were valid syntax.
You can't do data.query.pages.-1 for the same reason you can't do var -1;: -1 is not a valid identifier.
But that's not a problem.
foo.bar // Access member bar of object foo
is just a shortcut for
foo["bar"] // Access member bar of object foo
so you can do
data.query.pages["-1"]
You could even do
data["query"]["pages"]["-1"]
Bracket notation has nothing to with arrays, it's just another way to access properties. In fact, the reason why we can only use bracket notation for arrays is because of the evaluation rules: To use dot notation, the property name must be a valid identifier name.
Or simply put:
You can only use dot notation if the property name would be a valid variable name or a reserved word.
And -1 doesn't fall in that category (you can't do var -1 = 'foo'; for example).
Examples for invalid identifier names:
0foo, -foo, &bar
anything that doesn't start with a letter, _ or $
foo-bar, foo+bar, foo bar
anything that contains something that is not a letter, a digit, _ or $ (or fall into specific unicode ranges, see the spec).
However, using reserved words is possible, even though they can't be used as variables:
foo.if // valid
var if = 42; // invalid
What is the difference between this
var person = {
name: "Bob",
age: "99"
};
and this?
var person = {
"name": "Bob",
"age": "99"
};
Or do they mean the same thing? If they do, what if I want the key to be an object? How would I specify the object as the key if name means "name"?
There is no difference. Quotes are only necessary if you want to use a string as a property name, but that string is not a valid identifier. Further,
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation.
(source)
Object literal syntax is covered in-depth on MDN.
They are equivalent in this case, but the quoted version allows you to use keys that are not valid JS identifiers. For example, this does not work:
{ -test: 42 }
while this does:
{ "-test": 42 }
You cannot specify an object as the key no matter what.
They mean the same thing. Valid keys are identifiers, string literals, or numeric literals. See http://ecma-international.org/ecma-262/5.1/#sec-11.1.5
You can't yet use objects themselves as keys, but WeakMap objects as proposed for EcmaScript 6 will solve this. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
I bumbed into one of those moments when I just lose the focus and start wondering on a silly question:
var a = {
b: "value"
}
What is the typeof 'b' and I don't mean the typeof "value", but the actual Key labeled as b?
background:
I started wondering about this when I had to create a key which is a string:
var a = {
"b": "value"
}
because at a later point it is referenced as:
a["b"]
And then ended up wondering about the original question.
In object literal terms, b is a property. Properties are either strings or symbols in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters.
for (key in a) {
alert(typeof key);
//-> "string"
}
Property names are automatically coerced into a string. You can try this yourself by using a numeric literal as a property name.
var object = {
.12e3: 'wut'
};
object[.12e3]; // 'wut'
object['.12e3']; // undefined
object['120']; // 'wut'
// Let’s try another numeric literal:
object = {
12e34: 'heh'
};
object[12e34]; // 'heh'
object['12e34']; // undefined
object[1.2e35]; // 'heh'
object['1.2e35']; // undefined
object[1.2e+35]; // 'heh'
object['1.2e+35']; // 'heh'
For this reason, I’d recommend using only string literals for property names.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
b is a string, it's just a shorthand syntax, so you write
var a = {
b: "value"
}
instead of
var a = {
"b": "value"
}
Keep in mind that JavaScript objects are hash tables and the keys are just strings. You may omit the quotes around property names during declaration, but if you use reserved words for property names or any other name that happens to be an invalid identifier, such as starting with a digit, or containing spaces, you would have to wrap the property names in quotes:
var a = {
"1b": "value",
"b and c": "value",
"+12345": "value"
};
Also note that you can reference the properties of objects using the dot notation or the subscript notation regardless of whether quotes were used when they were declared. However, if you use property names that would be invalid identifiers, such as the ones in the above example, you are forced to use the subscript notation:
a.1b // invalid (dot notation)
a["b and c"]; // valid (subscript notation)
var a = {$ : 'hello', 2123 : 'number'};
for(var key in a) {
console.log(typeof key)
}
Keys in javascript objects can be strings and symbols. symbol is a primitive data type in javascript.