2

I'm wonder what is difference between result.id and result['id'] in Angular/JavaScript ? If i'm type :

getId(){
  this.service.getId().subscribe(
    result=>{ var i = result.id; }//this...
  )
}

...sometimes the compiler decorate result.id with red underline (error) then i change it to :

getId(){
  this.service.getId().subscribe(
    result=>{ var i = result['id']; }//with this
  )
}

the decoration disappear. But sometimes i can write result.id and not see any errors.

Note that the result type is any !!!

So i'm confused a little with 2 cases. Did i miss something ?

Thanks anyway!

Quan Truong
  • 193
  • 4
  • 11
  • 1
    from a code point of view, nothing. Whatever editor you're using is doing that – Bravo Oct 07 '19 at 03:37
  • 1
    Both `result.id` and `result['id']` are same – Code Maniac Oct 07 '19 at 03:38
  • If you want not mark as error "cast" to any: `subscribe((res:any)=>{let i=result.id})`: NOTE try use "let", not "var" to define a variable, else the variable can be propagate along the application – Eliseo Oct 07 '19 at 06:43

3 Answers3

2

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

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:

1. Dot notation is faster to write and clearer to read.
2. 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
Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18
1

Value is same in both the cases, the difference has been correctly pointed out by @Suneet Bansal. May be linter in your case is causing the error.

Anand Bhushan
  • 765
  • 8
  • 18
-1

It depends, you are using an Object or an Array. Dot notation works while using an Object it will throw an error if using square bracket sometimes

Rakesh Singh
  • 211
  • 1
  • 5
  • 15