Dot and Square Bracket Notation

JavaScript property access: dot notation vs. brackets?

(Sourced from here.)

Square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

including non-ASCII (UTF-8) characters, as in myForm["ダ"] (more examples).

Secondly, square bracket notation is useful when dealing with
property names which vary in a predictable way:

for (var i = 0; i < 10; i++) {
someFunction(myForm["myControlNumber" + i]);
}

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing
    special characters and selection of
    properties using variables

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

What's the difference between the square bracket and dot notations in Python?

The dot operator is used for accessing attributes of any object. For example, a complex number

>>> c = 3+4j

has (among others) the two attributes real and imag:

>>> c.real
3.0
>>> c.imag
4.0

As well as those, it has a method, conjugate(), which is also an attribute:

>>> c.conjugate
<built-in method conjugate of complex object at 0x7f4422d73050>
>>> c.conjugate()
(3-4j)

Square bracket notation is used for accessing members of a collection, whether that's by key in the case of a dictionary or other mapping:

>>> d = {'a': 1, 'b': 2}
>>> d['a']
1

... or by index in the case of a sequence like a list or string:

>>> s = ['x', 'y', 'z']
>>> s[2]
'z'
>>> t = 'Kapow!'
>>> t[3]
'o'

These collections also, separately, have attributes:

>>> d.pop
<built-in method pop of dict object at 0x7f44204068c8>
>>> s.reverse
<built-in method reverse of list object at 0x7f4420454d08>
>>> t.lower
<built-in method lower of str object at 0x7f4422ce2688>

... and again, in the above cases, these attributes happen to be methods.

While all objects have some attributes, not all objects have members. For example, if we try to use square bracket notation to access a member of our complex number c:

>>> c[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'complex' object is not subscriptable

... we get an error (which makes sense, since there's no obvious way for a complex number to have members).

It's possible to define how [] and . access work in a user-defined class, using the special methods __getitem__() and __getattr__() respectively. Explaining how to do so is beyond the scope of this question, but you can read more about it in the Python Tutorial.

How to use variables in dot notation like square bracket notation with variable depth

You can create a function that will split the string with . (dot) as the delimiter into an array of strings, and use them to traverse the object in a reducer function.

const item = {
"car": {
"manufacturer": "Ford",
"model": "Taunus",
"surface": {
"color": "silver",
"type": "metallic"
},
"built (year)": "1975"
}
}

const foo = "car.model";
const bar = "car.surface.color";

function get(path) {
const parts = path.split(".");
return parts.reduce((obj, part) => obj[part], item);
}

get(foo); // should return "Taunus"
get(bar); // should return "silver"

Dot and Square Bracket Notation

In dot notation, the name after the dot is the name of the property being referenced. So:

var foo = "bar";
var obj = { foo: 1, bar: 2 };

console.log(obj.foo) // = 1, since the "foo" property of obj is 1,
// independent of the variable foo

However, in square-bracket notation, the name of the property being referenced is the value of whatever is in the square brackets:

var foo = "bar";
var obj = { foo: 1, bar: 2 };

console.log(obj[foo]) // = 2, since the value of the variable foo is "bar" and
// the "bar" property of obj is 2

console.log(obj["foo"]) // = 1, since the value of the literal "foo" is "foo" and
// the "foo" property of obj is 1

In other words, dot-notation obj.foo is always equivalent to obj["foo"], while obj[foo] depends on the value of the variable foo.


In the specific case of your question, note the differences between dot notation and square-bracket notation:

// with dot notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;

obj.key = value; // referencing the literal property "key"
console.log(obj) // = { name: "John Doe", age: 30, key: 60 }

// with square bracket notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;

obj[key] = value; // referencing property by the value of the key variable ("age")
console.log(obj) // = { name: "John Doe", age: 60 }

difference between dot notation and bracket notation in javascript

When you use dot notation, key means the actual property in the object, which will not be there. So, undefined is returned which is not equal to true.

When you use [] notation you are accessing the property in the object with the name in the variable key. So, that will work.

For example,

var myObj = {
myVar : 1
};

for (var key in myObj) {
console.log(key);
console.log(myObj.key);
console.log(myObj[key]);
}

This will print,

myVar
undefined
1

Because, myObj has no member named key (myObj.key tries to get the member with the name key) and in the next case, myObj has a member named myVar (myObj[key] tries to get the member with the value in key).

Dot Notation

jslint prefers dot notation.

[] Notation

This offers flexibility. You can dynamically access the members with a variable.

Javascript Dot Notation vs Bracket Notation

for(var key in sunny){
console.log(sunny.key)
}

sunny.key in bracket notation is equivalent to sunny["key"]. It is searching for a property name "key" which is not there in your object.Hence returning undefined always.

key here is actually variable , not a string to extract the value of a property.

See : https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781

Difference between using bracket (`[]`) and dot (`.`) notation

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.

javascript - dot vs bracket notation in enumeration

It is not working because there is no speargun property in the rockSpearguns object.

The reason is that in a JS object, all property keys are strings. When you use dot notation, JS is thinking you are looking for a key with the explicit key of whatever is after the dot.

In your code var speargun is being replaced with a string value of each of the properties inside the rockSpearguns object.

So, guns[speargun].heft translates to guns["Sharpshooter"].heft

I suggest you to read this article.

JS Objects: dot notation inside bracket notation, lists inside bracket notation

Each index has to be enclosed by it's own brackets.

To access those objects with those paths, use

myob["title"]
myob["list"][0]
myob["myObject"]["objectTitle"]


Related Topics



Leave a reply



Submit