JavaScript: Access/List Properties

By Xah Lee. Date: . Last updated: .

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. 〔➤see 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. 〔➤see JavaScript: Prototype and 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
delete o["p"]Delete a property p in o if it exists. ECMAScript 5.1 §11#sec-11.4.1no
o.hasOwnProperty("p")true if the object has the
p in otrue if is own property or in prototype chain. ECMAScript 5.1 §11#sec-11.8.7 yes

〔➤see JavaScript: Dot Notation vs Bracket Notation for Accessing Properties〕 〔➤see JavaScript: Prototype and 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 and enumerable.noyes
for (var p in o) {…}loop thru all enumerable properties in the prototype chain, set the property name to p. Order is not guaranteed.yesyes

〔➤see 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

Avoid using the for x in obj because you probably don't want to go thru prototype-chain. Use Object.getOwnPropertyNames() or Object.keys() instead.

// loop thru enumerable own properties of a object.

var obj = {"a":3, "b":4};

    function (k) {
        console.log(k, obj[k]); // key and value

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

〔➤see JavaScript: Array Methods

back to JavaScript: Property Overview

Like what you read? Buy JavaScript in Depth
or, buy something from my keyboard store