In JavaScript, if you type
typeof("2")
you should get string.
And if you type
typeof(2)
you should get number.
Now my question is, it is said that when you define an object, the key must be a string.
so this is legal
apple = {"color":"red"}
However, if I change the key to a number wrapped in the inverted commas, it should work as anything inside of inverted commas
apple={"2": "red"}
But If I call the object property, apple.2, this will fail with error Unexpected number.
so am just curious, what am I missing here while defining the objects in JavaScript.
An object key must be a string, but JavaScript allows you to assign an object with a number. It's just converted to a string behind the scenes, so:
apple = {2: "red"}
is the same as:
apple = {"2": "red"}
Using dot notation requires a valid identifier. So you can not access the property with apple.2 as 2 is a number, instead, you have to use bracket notation, either apple["2"] or apple[2].
Incidentally, there are other cases which can not be accessed with dot notation, such as:
apple = {"hyphenated-key": true}
Trying to access apple.hyphenated-key would not work, you have to use bracket notation as such apple["hyphenated-key"].
Related
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)
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)
I'm building out a component that accepts an input of dot notation. I want to validate the input and when I stopped to think about "what is valid dot notation" I figured this would be a simple way of doing it, but it almost seems too simple so now I'm wondering if I'm missing something:
function isValidDotNotation(content: string) {
try {
content.split(".")
return true
} catch (exception) {
return false
}
}
So:
dot notation is a way of specifying a namespace within a json data structure then it seems like our main concern is validating keys
JSON requires strings for keys
the split static method hangs off of String so you'd only be able to fire it on a string
Specifying an array index in dot notation just makes the square brackets part of a string (e.g. in example.widgets[0].name, widgets[0] is still a valid string when .split()
A single level dot notation string can still be split into a single array value (e.g. "test".split(".") still works)
So when we fire split, as long as we don't throw an exception the the string given should be a valid dot notation. It may or may not lead you to anything within the json structure, but as far as a valid value it should be good, right?
Am I missing any nuance here? I've seen examples of people looping through the structure and stuff, but it seems like overkill to validate unless I'm missing something.
string.split will never throw an exception when passed a string. Therefore, via these rules, any string is valid dot notation. In that case you only need to verify whether something is a string, which you can do like so:
typeof content === 'string'
You're missing something. Your original code won't work with the input:
content1 = "example.widgets[.0].name"
content2 = "example.widgets[0].name."
I have the following object self.originalData on the console:
However, when I try to access to first object in the array of originalData,
self.originalData[0hcMSJXljH]
getting the following error
the Uncaught>Syntax Error: Unexpected token ILLEGAL
I could not able to figure out where I am doing wrong.
You can use:
self.originalData["0hcMSJXljH"]
instead. Object keys are strings so if you use the [] notation, then you have to put a string or a variable that contains a string inside the brackets.
Your particular case is a bit unusual because usually, you can use the dot notation as in obj.property, but because your key starts with a number, it is not a legal identifier to use with the dot notation (you can't do self.originalData.0hcMSJXljH). So, you are forced to use the bracket notation with that particular key.
Try putting the key in quotes like this:
self.originalData['0hcMSJXljH']
You don't use quotes in your key, so it seems you are trying to use the variable identified by 0hcMSJXljH as the key. However, 0hcMSJXljH isn't a valid variable identifier, because it begins with a number, so your get an illegal-character error.
Simply use a string, not an identifier:
self.originalData["0hcMSJXljH"]
Have you tried
self.originalData["0hcMSJXljH"];
?
Otherwise:
self.originalData.0hcMSJXljH;
EDIT: last one not possible because the first char is a number, as explained to me
You must use quotes:
self.originalData['0hcMSJXljH']
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)