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

const o1 = {"p1":1};

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

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

const 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.

const 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

JS Object Property

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

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc