JavaScript: Accessing & Listing Properties

, , …,
Buy Xah JavaScript Tutorial.

This page gives a summary of operations on object properties. Some will travese the prototype chain, some not, some depend on whether the property's enumerable attribute is true. 〔➤ JavaScript: Property Attributes: Writable, Enumerable, Configurable

First, remember that in JavaScript, each object has a parent, and parent also has parent, forming a prototype chain. When looking up a property, JavaScript'll check the object's property, if not found, then check its parent, up the prototype chain, until a parent is null. 〔➤ JavaScript: Understanding Prototype & Inheritance

Property Operations: Access, Set, Delete, Check Existence

Here's a summary of operations on property.

JavaScript property operations
syntaxmeaningproto chain
o["p"]Return the value of the property.yes
o["p"] = valueModify or create a new property for the object.no
delete o["p"]Delete a property p in o if it exists.no
o.hasOwnProperty("p")true if the object has the property.no
p in otrue if is own property or in prototype chain.yes

〔➤ JavaScript: Dot Notation vs Bracket Notation for Accessing Properties〕 〔➤ JavaScript: Understanding Prototype & Inheritance

Listing Properties

Here's a summary of ways to list or loop thru properties.

JavaScript property listing operations
syntaxmeaningproto chainenumerable only
Object.getOwnPropertyNames(o)Return a array of all own property names. (including non-enumerable ones)nono
Object.keys(o)Return a array of property names that are own & enumerable.noyes
for (var x in o) {…}loop thru all enumerable properties in the prototype chain, set the property name to x. Order is not guaranteed.yesyes

〔➤ JavaScript: Property Attributes: Writable, Enumerable, Configurable

// List all enumerable properties in prototype chain or own

var o1 = {"a":3};

// create object o2, with parent o1
var o2 = Object.create(o1); 
o2["b"] = 4;

for (var pp in o2) {
    console.log( pp, o2[pp]);
}

// prints
// b 4
// a 3

〔➤ JavaScript: Creating Object with Object.create()

〔➤ JavaScript Array Methods

back to JavaScript: Property Overview

blog comments powered by Disqus