How bracket notation in javascript access the property of an object? - javascript

Consider below example:
a={
'firstProperty': "first",
'secondProperty':"second"
};
console.log(a[[[["firstProperty"]]]]);
by using multiple bracket notation i am able to access the firstProperty. How bracket notation is accessing this property??

You are using a nested array and by using a non string or symbol as value, the value is converted to string.
console.log([[["firstProperty"]]].toString());

Because what you provide as the key in a property accessor expression is converted to string if it isn't a Symbol or a string. console.log(a[[[["firstProperty"]]]]); uses an array of arrays as the property name in the accessor expression. Since that isn't a Symbol, it's converted to string. When you convert your array to string, you get the string "firstProperty" because that's how Array.prototype.toString works:
console.log(String([[["firstProperty"]]]));
...and "firstProperty" correctly identifies one of the properties in the object, so the property accessor expression gives you the value of that property.
Using an array like that is unnecessary. Just use
console.log(a["firstProperty"]);
or
console.log(a.firstProperty);

Related

ES6 Symbols with Dot Notation

In the examples I've seen so far using Symbols in ES6, you have to access symbol properties in Object literals using bracket notation:
let mySymbol = Symbol("mySymbol");
let someObject = {
[mySymbol]: "someValue"
};
console.log(someObject[mySymbol]); // "someValue"
Is there a way to define and access symbol properties using dot notation?
No. Symbols must be accessed using bracket notation.
Dot notation is only used for string keys that follow certain rule patterns, mostly about being a valid identifier.
Symbols are not strings, they are a whole something else entirely.
Short rational: One of the design goals of symbols is that they can not clash with property names, that makes them safe to use.
So, if you had an object like this
var = {
prop1: "Value"
};
And you created a symbol called prop1, how could you tell the two apart, and access them differently, using just object notation?
No. Dot notation is reserved for identifiers which resolve to property names (strings). And this won't change for backward compatibility reasons.

AngularJS at symbol (#) object inside locals variable [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)

How to convert string to var name at function call

I find myself needing to convert a string var (in JavaScript) to a variable name that is called when getting an element. My spontaneous solution to this was writing:
this.name = name;
[...]
this.context.drawImage(imageRepository.(this.name), this.x, this.y);
This does not work however, returning "Unexpected token (". Any suggestions?
You're looking for a property name, not a variable name. You can use bracketed notation for that:
imageRepository[this.name]
In JavaScript, you can refer to properties in two ways: Using dot notation and a property name literal (obj.foo), or using bracketed notation and a property name string (obj["foo"]). In the latter case, the string can be the result of any expression, including looking up a property on another object (this.name).
You need bracket notation in this case.
imageRepository[this.name]
The bracket notation evaluates the variable and selects the appropriate property.

What does Object(this) do?

I noticed in several MDN Array method shims, such as this one on line 7, that they use the following syntax:
var t = Object(this);
Where this is an array. Not only does it not hint in my validator, I’m also clueless as to what it does.
Can anyone shed a light?
As far as I can tell, the only use of it in there is to cover the case when you pass a string literal to Array.prototype.indexOf. If you remove it and pass a string in you get an error:
TypeError: Cannot use 'in' operator to search for '0' in string
However, by casting the string literal to an instance of String, you end up with an object with a numerical property for each character of the string, and since it's a normal object, you can use the in operator on it and the method will return the index of the character in the string:
Array.prototype.indexOf.call("hello", "e"); // Returns 1
Here's an example with the cast to Object, and here's an example without it.
In more general cases, passing anything to the Object constructor will attempt to convert that thing to an object. So you can pass it a string literal and get an instance of String back, or pass it a numeric literal and get an instance of Number.

String to jQuery.function

What's the simplest way to call a string method with jquery?
If I understand your question correctly, you want to call a method whose name is stored in a string.
If that's the case, you should use square bracket notation instead of (not in addition to) dot notation, and delimit the literal string with quotes:
$["STRINGVALUE"]();
You can also use the variable you defined initially, without quotes:
$[myFunction]();

Categories