js variable assign array or object

When we sometime create  a library we have to assign some a variable as object or array.

var man = {
name : {
first : '',
last : ''
},
children : {},
toString : function () {
return this.name.first + ' ' + this.name.last + ' has ' + this.children.length + ' children and they are ' + this.children;
}
};
man.name.first = 'Arif Mahmud', man.name.last = 'Rana';
man.children.push('Fatima');

When run on firebug
When run on firebug

Will I assign as an array or object


var man = {
name : {
first : '',
last : ''
},
children : [],
toString : function () {
return this.name.first + ' ' + this.name.last + ' has ' + this.children.length + ' children and they are ' + this.children;
}
};
man.name.first = 'Arif Mahmud', man.name.last = 'Rana';
man.children.push('Fatima');
alert(man);

Output :

image-2

 

What happens here

There is no JavaScript error.  When we children to array it solves the problem. When we call push method on children it throws error because it was declared as an object not as an array. So push method isn’t available for object.

Tips

Always declare variable as an array rather object. Because than you can access array methods.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s