Shohel
Shohel

Reputation: 3934

Get Object Property Value in JavaScript

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.

Upvotes: 0

Views: 65

Answers (1)

yunandtidus
yunandtidus

Reputation: 4086

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

Upvotes: 2

Related Questions