0

I am using get property value in JavaScript by this way

$(document).ready(function () {
            var itemList = [{ id: 1, name: 'shohel' }, { id: 2, name: 'rana' }, { id: 3, name: 'shipon' }];

            //step 1 : get property value
            for (var i = 0; i < itemList.length; i++) {
                var id = itemList[i].id;
            }

            //step 2 : get property value
            for (var i = 0; i < itemList.length; i++) {
                var id = itemList[i]['id'];
            }

            //which is better?
        });

I can not understand which is better syntax for get property value in javaScript? Thanks.

Shohel
  • 3,886
  • 4
  • 38
  • 75

1 Answers1

2

Both are correct use.

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

In my opinion, for this usage the first one is the best one. And the second one should be used when index is a variable (computed before), ex :

var index = 'id';
var id = itemList[i][index]; 

And in this case, your second solution is the only way of doing it, and by the way the better one

Shohel
  • 3,886
  • 4
  • 38
  • 75
yunandtidus
  • 3,847
  • 3
  • 29
  • 42
  • Thanks your reply, but if i want to check unknown property suppose var index = 'age'; var age = itemList[i].age, it will be error because age is not the property of that object, according to all of the case, which is better? – Shohel Oct 16 '14 at 07:46
  • It is not an error, it is undefined. And without the use of variable, even if this case (undefined index), both your solutions are equals. – yunandtidus Oct 16 '14 at 07:50
  • How can i measure? which is faster? – Shohel Oct 16 '14 at 08:19