JS: Get Property, Set Property

By Xah Lee. Date: . Last updated: .

Reading Property Goes Up the Prototype Chain

When a property of a object is looked up (For example, obj.color), JavaScript first look at the object to see if it has that property, if not, it lookup its parent, and repeat, until a property is found or parent object is null. This is the technical meaning of inheritance.

// accessing property goes up the prototype chain

var o1 = {"p1":1};

// create object o2, with o1 as parent
var o2 = Object.create(o1);

console.log(o2["p1"]);          // 1 , from o1
// accessing property goes up the prototype chain

var o1 = {};
console.log(o1["toString"]);    // [Function: toString]

// the property toString is from Object.prototype.toString , shows up because Object.prototype is in the prototype chain of any object

Accessing Non-Existent Property Returns “undefined”

// accessing non-existent property returns undefined
console.log({a:2}.a); // 2
console.log({a:2}.b); // undefined

Setting Property Never Touches Prototype Chain

When you set a property, it does not touch the prototype chain. If the object has the property, its value is modified. If the object does not have the property, it's created for the object.

// setting a property will not touch prototype chain.

var bb = {"p1":1};

// bb inherited the property key toString
console.log("toString" in bb);              // true
console.log(bb["toString"]);                // [Function: toString]
console.log(bb.hasOwnProperty("toString")); // false

// set the property key toString
bb["toString"] = 2;
console.log(bb["toString"]);                // 2
console.log(bb.hasOwnProperty("toString")); // true

There are many JavaScript {operator, statement, method}, that {access, set, list, loop} properties. Some traverse the prototype chain, some do not, and some depend on whether the enumerable attribute of the property is true.

See: JS: Access Property, List Properties

JS Object Property Topic

  1. JS: Property Overview
  2. JS: Property Key
  3. JS: Property Dot Notation / Bracket Notation
  4. JS: Create/Delete Property
  5. JS: Get Property, Set Property
  6. JS: Check Property Existence
  7. JS: Access Property, List Properties
  8. JS: Property Attributes
  9. JS: Getter/Setter Properties
  10. JS: Property Descriptor
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth