JavaScript: Access/List Properties

By Xah Lee. Date: . Last updated: .

This page shows all the ways to work with properties.

Access, Set, Delete, Check Existence

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. ECMAScript 5.1 §11#sec-11.4.1no
o.hasOwnProperty(p)true if the object has the property.no
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

List Properties, Enumerate 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
for (var v of iterable) {…} loop thru values of iterable object iterable. 〔➤see JavaScript: for-of Loop (ES2015)N/AN/A

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

Tip: Avoid Using 「for x in obj」

Avoid using 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};

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

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

〔➤see JavaScript: Array Methods

Property topics:

  1. JavaScript: Property Overview
  2. JavaScript: Property Key
  3. JavaScript: Dot Notation vs Bracket Notation for Accessing Properties
  4. JavaScript: Create/Delete Property
  5. JavaScript: Read/Write to Property and Prototype Chain
  6. JavaScript: Check Property Existence
  7. JavaScript: Access/List Properties
  8. JavaScript: Property Attributes: Writable, Enumerable, Configurable
  9. JavaScript: Getter/Setter Properties
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.