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
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
What is the difference between accessing a JSON object using period (.) and [] notation in Javascript. For instance,
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
I'm sure accessing the "firstName" and the "lastName" variables give me the same output type (string),i.e.
console.log(typeof person.firstName); // returns string
console.log(typeof person.lastName); // returns string
Also, accessing it both the ways, using . or [] will give me the same result:
console.log(person.firstName); // returns Foo
console.log(person['firstName']); // returns Foo
I'm trying to understand when to use which notation and when not to and the actual difference between them. I read somewhere that we can't use the dot notation if the data is complicated, I'm not sure what it means, tested out a couple of sample input data:
"firstName": " Foo Bar "
"firstName": "####$% Foo Bar!!!"
Interestingly, both gives me the same result, can someone please explain me what's the actual difference between these two notations and when to access which?
They are both valid ways of accessing Object Values.
Welcome to Stackoverflow!
The main difference between the two is that using bracket notation allows you to define and access properties with spaces in them -- something one cannot do with dot notation.
var foo = {
"I AM BAR": 1
}
If you wanted to access the single property "I AM BAR" on foo, with bracket notation, it would look like: foo["I AM BAR"]. This is not possible with dot notation.
There are not difference.
The [] approach is useful when you need find a key with a variable.
Like:
const theKey = 'test';
theArray[theKey]; // this work
theArray.theKey; // this dont work
Using dot notation you must provide the exact propertyName but you are able to work with the name when using [].
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
Using . you can only access by
console.log(person.firstName); // returns Foo
Using [] you could access value with variable
let couldChange = 'Name';
console.log(person['first'+couldChange]); // returns foo
console.log(person['last'+couldChange]); // returns bar
Most of the time you will use dot notation. Unless you need the property on the object you need to access to be dynamic. This is because the value you pass into the brackets could be a variable as long it resolves to a string. Check out this link for more info:
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Most of the time, there's no difference, see Property accessors (MDN), but you cannot use dot notation when the property name is not a valid identifier name, e.g. when it's representation is not a string, or when you need to use a variable to name the property.
obj[1] // is valid
obj["1"] // is the same
obj.1 // is NOT valid
const propertyName = 1;
obj[propertyName] // the same as obj[1]
obj.propertyName // not same
Using brackets can allow you to use a variable value to access object properties whereas dot notation won't. For example:
var propName = 'age';
var o = {
name: 'Tom',
age: '29',
about: 'He\'s a cool guy!'
};
console.log(o.propName); // <-- Will be undefined
console.log(o[propName]); // <-- Bingo
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 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
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.
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.