Difference Between Using Bracket ('[]') and Dot ('.') 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

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.

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.

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.

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

What are these three dots in React doing?

That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).

{...this.props} spreads out the "own" enumerable properties in props as discrete properties on the Modal element you're creating. For instance, if this.props contained a: 1 and b: 2, then

<Modal {...this.props} title='Modal heading' animation={false}>

would be the same as

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>

But it's dynamic, so whatever "own" properties are in props are included.

Since children is an "own" property in props, spread will include it. So if the component where this appears had child elements, they'll be passed on to Modal. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a children property in the opening tag. Example:

class Example extends React.Component {  render() {    const { className, children } = this.props;    return (      <div className={className}>      {children}      </div>    );  }}ReactDOM.render(  [    <Example className="first">      <span>Child in first</span>    </Example>,    <Example className="second" children={<span>Child in second</span>} />  ],  document.getElementById("root"));
.first {  color: green;}.second {  color: blue;}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

  • How does the "this" keyword work?

var x = function() vs. function x()  —  Function declaration syntax

  • var functionName = function() {} vs function functionName() {}

(function(){})()  —  IIFE (Immediately Invoked Function Expression)

  • What is the purpose?, How is it called?
  • Why does (function(){…})(); work but function(){…}(); doesn't?
  • (function(){…})(); vs (function(){…}());
  • shorter alternatives:
    • !function(){…}(); - What does the exclamation mark do before the function?
    • +function(){…}(); - JavaScript plus sign in front of function expression
    • !function(){ }() vs (function(){ })(), ! vs leading semicolon
  • (function(window, undefined){…}(window));

someFunction()()  —  Functions which return other functions

  • Two sets of parentheses after function call

=>  —  Equal sign, greater than: arrow function expression syntax

  • What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

|>  —  Pipe, greater than: Pipeline operator

  • What does the "|>" operator do in JavaScript?

function*, yield, yield*  —  Star after function or yield: generator functions

  • What is "function*" in JavaScript?
  • What's the yield keyword in JavaScript?
  • Delegated yield (yield star, yield *) in generator functions

[], Array()  —  Square brackets: array notation

  • What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
  • What is array literal notation in javascript and when should you use it?

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value}  —  Curly brackets: object literal syntax (not to be confused with blocks)

  • What do curly braces in JavaScript mean?
  • Javascript object literal: what exactly is {a, b, c}?
  • What do square brackets around a property name in an object literal mean?
  • How does this object method definition work without the "function" keyword? (ES2015 Method definitions)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}`  —  Backticks, dollar sign with curly brackets: template literals

  • What does this `…${…}…` code from the node docs mean?
  • Usage of the backtick character (`) in JavaScript?
  • What is the purpose of template literals (backticks) following a function in ES6?

//  —  Slashes: regular expression literals

  • Meaning of javascript text between two slashes

$  —  Dollar sign in regex replace patterns: $$, $&, $`, $', $n

  • JavaScript replace() method dollar signs

()  —  Parentheses: grouping operator

  • MDN: Grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"]  —  Square brackets or dot: property accessors

  • JavaScript property access: dot notation vs. brackets?

?., ?.[], ?.()  —  Question mark, dot: optional chaining operator

  • Question mark after parameter
  • Null-safe property access (and conditional assignment) in ES6/2015
  • Optional Chaining in JavaScript
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

::  —  Double colon: bind operator

  • JavaScript double colon (bind operator)

new operator

  • What is the 'new' keyword in JavaScript?
  • What is "new.target"?

...iter  —  Three dots: spread syntax; rest parameters

  • (...rest) => {}  —  What is the meaning of “…args” (three dots) in a function definition?
  • fn(...args)  —  What is the meaning of “foo(…arg)” (three dots in a function call)?
  • [...iter]  —  javascript es6 array feature […data, 0] “spread operator”
  • {...props}  —  Javascript Property with three dots (…), What does the '…rest' stand for in this object destructuring?


Increment and decrement

++, --  —  Double plus or minus: pre- / post-increment / -decrement operators

  • ++someVariable vs someVariable++ in Javascript


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

  • What is the purpose of the delete operator in Javascript?

void operator

  • What does `void 0` mean?

+, -  —  Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

  • What does = +_ mean in JavaScript, Single plus operator in javascript
  • What's the significant use of unary plus and minus operators?
  • Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
  • Why does JavaScript handle the plus and minus operators between strings and numbers differently?

|, &, ^, ~  —  Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

  • What do these JavaScript bitwise operators do?
  • How to: The ~ operator?
  • Is there a & logical operator in Javascript
  • What does the "|" (single pipe) do in JavaScript?
  • What does the operator |= do in JavaScript?
  • What does the ^ (caret) symbol do in JavaScript?
  • Using bitwise OR 0 to floor a number, How does x|0 floor the number in JavaScript?
  • Why does ~1 equal -2?
  • What does ~~ ("double tilde") do in Javascript?
  • How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call? (also here and here)

%  —  Percent sign: remainder operator

  • What does % do in JavaScript?

&&, ||, !  —  Double ampersand, double pipe, exclamation point: logical operators

  • Logical operators in JavaScript — how do you use them?
  • Logical operator || in javascript, 0 stands for Boolean false?
  • What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?, JavaScript OR (||) variable assignment explanation, What does the construct x = x || y mean?
  • Javascript AND operator within assignment
  • What is "x && foo()"? (also here and here)
  • What is the !! (not not) operator in JavaScript?
  • What is an exclamation point in JavaScript?

??  —  Double question mark: nullish-coalescing operator

  • How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

**  —  Double star: power operator (exponentiation)

  • x ** 2 is equivalent to Math.pow(x, 2)
  • Is the double asterisk ** a valid JavaScript operator?
  • MDN documentation


Equality operators

==, ===  —  Equal signs: equality operators

  • Which equals operator (== vs ===) should be used in JavaScript comparisons?
  • How does JS type coercion work?
  • In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so?
  • [] == ![] evaluates to true
  • Why does "undefined equals false" return false?
  • Why does !new Boolean(false) equals false in JavaScript?
  • Javascript 0 == '0'. Explain this example
  • Why false == "false" is false?

!=, !==  —  Exclamation point and equal signs: inequality operators

  • != vs. !==
  • What is the difference between != and !== operators in JavaScript?


Bit shift operators

<<, >>, >>>  —  Two or three angle brackets: bit shift operators

  • What do these JavaScript bitwise operators do?
  • Double more-than symbol in JavaScript
  • What is the JavaScript >>> operator and how do you use it?


Conditional operator

?:…  —  Question mark and colon: conditional (ternary) operator

  • Question mark and colon in JavaScript
  • Operator precedence with Javascript Ternary operator
  • How do you use the ? : (conditional) operator in JavaScript?


Assignment operators

=  —  Equal sign: assignment operator

  • What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)

This symbol is also used for default parameters or default values in a destructuring assignment:

  • what does (state = {}) => state means
  • What does ({"key": "value"} = {}) syntax mean inside a JavaScript function

%=  —  Percent equals: remainder assignment

  • Having Confusion with Modulo operator

+=  —  Plus equals: addition assignment operator

  • How does += (plus equal) work?

&&=, ||=, ??=  —  Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

  • What purpose do &&=, ||= and ??= serve?
  • Replace a value if null or undefined in JavaScript
  • Set a variable if undefined
  • Ruby’s ||= (or equals) in JavaScript?
  • Original proposal
  • Specification

<<=, >>=, >>>=, &=, ^=, |= — Double less than, double greater than, triple greater than, ampersand, caret, or pipe followed by equal sign: bitwise assignments

  • What do these JavaScript bitwise operators do?

Destructuring

  • of function parameters: Where can I get info on the object parameter syntax for JavaScript functions?
  • of arrays: Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?
  • of objects/imports: Javascript object bracket notation ({ Navigation } =) on left side of assign


Comma operator

,  —  Comma operator (not to be confused with the comma used in variable declarations)

  • What does a comma do in JavaScript expressions?
  • Comma operator returns first value instead of second in argument list?
  • When is the comma operator useful?


Control flow

{}  — Curly brackets: blocks (not to be confused with object literal syntax)

  • JavaScript curly braces with no function or json

Declarations

var, let, const  —  Declaring variables

  • What's the difference between using "let" and "var"?
  • Are there constants in JavaScript?
  • What is the temporal dead zone?
  • var a, b;  —  Comma used in variable declarations (not to be confused with the comma operator): JavaScript variable definition: Commas vs. Semicolons


Label

label:  —  Colon: labels

  • What does the JavaScript syntax foo: mean?
  • What does ':' (colon) do in JavaScript?


Other

123n  —  n after integer: BigInt

  • What does character 'n' after numeric literal mean in JavaScript?

#  —  Hash (number sign): Private methods or private fields

  • What does the # symbol do in JavaScript?

_  —  Underscore: separator in numeric literals

  • Javascript numeric separators?
  • Is there a Javascript equivalent to the Ruby syntax using underscores (e.g. 10_000 = 10000) to make larger integers human readable?

Difference between dot notation and square brackets in Flask templates

This is a feature of Jinja2, see the Variables section of the Template Designer documentation:

You can use a dot (.) to access attributes of a variable in addition to the standard Python __getitem__ “subscript” syntax ([]).

This is a convenience feature:

For the sake of convenience, foo.bar in Jinja2 does the following things on the Python layer:

  • check for an attribute called bar on foo (getattr(foo, 'bar'))
  • if there is not, check for an item 'bar' in foo (foo.__getitem__('bar'))
  • if there is not, return an undefined object.

foo['bar'] works mostly the same with a small difference in sequence:

  • check for an item 'bar' in foo. (foo.__getitem__('bar'))
  • if there is not, check for an attribute called bar on foo. (getattr(foo, 'bar'))
  • if there is not, return an undefined object.

This is important if an object has an item and attribute with the same name. Additionally, the attr() filter only looks up attributes.

So if you use the attribute access ({{ session.username }}) then Jinja2 will first look for the attribute, then for the key. Since the Flask session object is a dictionary, this means you could potentially end up with the wrong result; if you have stored data under the key get in the session, session.get returns a dictionary method, but session['get'] would return the actual value associated with the 'get' key.



Related Topics



Leave a reply



Submit