JS: Object Basics

By Xah Lee. Date: . Last updated: .

JavaScript object is a collection of key/value pairs.

Each key/value pair of a object is called property. [see JS: Property Overview]

Properties are unordered, and values can be changed anytime, and property can be added or removed, anytime.

Each object automatically inherit parent object's properties.

JavaScript objects are used for 2 purposes:

Creating Object

The literal expression to create a object has this syntax:

{name_1:val_1, name_2:val_2, …}

// creating a object with 3 properties
const nn = {"cat":19, "dog":20, "rabbit":25};

Access Property

2 syntax to access property:

// creating a object
const nn = {"cat":19, "dog":20, "rabbit":25};

// Accessing property, bracket notation
nn["cat"] // 19

// Accessing property, dot notation
nn.cat // 19

[see JS: Property Dot Notation / Bracket Notation]

Adding Properties

Create a empty object, then add some properties:

const oj = {}; // creating a object
oj.c1 = 3;    // add a property c1
oj.c2 = 4;

console.log(oj); // { c1: 3, c2: 4 }

Change a Property's Value

const obj =  {"1": "a", "2": "c"};

obj["2"] = "b";

console.log( obj); // { '1': 'a', '2': 'b' }

Delete a Property

To delete a property, use the operator delete.

const nn = {"cat":19, "dog":20, "rabbit":25};
delete nn["cat"]; // delete a property
console.log(nn); // { dog: 20, rabbit: 25 }

Loop-Thru Object's Properties

Object.getOwnPropertyNames(obj) return all property names as a array, then use forEach to loop thru them.

Object.keys(obj) return all enumerable property names as array, then use forEach to loop thru them.

const nn = {"a":19, "c":20, "b":25};

// loop thru object's own properties, including non-enumarable properties
Object.getOwnPropertyNames(nn).forEach(
    function(x) {
        console.log(x); // name
        console.log(nn[x]); // value
    }
)

// loop thru object's own properties, for enumarable properties only
Object.keys(nn).forEach(
    function(x) {
        console.log(x); // name
        console.log(nn[x]); // value
    }
)

Note: each JavaScript property has “attributes”, and one of them is enumerable. Its value is true or false. Which property will show in a loop construct dependes on this value, and the loop construct.

[see JS: Property Attributes, writable, enumerable, configurable]

To loop thru a object's enumerable properties and its inherited enumerable properties, use for (var x in object) {…}. The x will be the value of each property in the loop body.

const nn = {"a":19, "c":20, "b":25};

// loop thru a object's enumerable properties and its inherited enumerable properties
for (const x in nn) {
    console.log(x);     // prints each key
    console.log(nn[x]); // prints each value
}

Note: JavaScript object has inherihance. [see JS: Prototype and Inheritance]

Note: when properties is looped thru, order is not guaranteed, but usually, older property comes first, and object's own property comes before inherited property.

For more about looping thru properties, see: JS: Access Property

Get All Keys of Object

Object.keys(obj) → Return a array of property names that are obj's own properties, and their “enumerable” attributes are true.

const j = {"a":19, "c":20, "b":25};
console.log( Object.keys(j) ); // prints [ 'a', 'c', 'b' ]

Nested Array and Object

Because object's property's value can be any object data type, so you can have any nested array and object. (because array is also a object. [see JS: Understand JS Array])

// Key/Value, with one value being array:
const x = {"a":19, "b":20, "c":[3,4]};
console.log( x["c"][0]); // prints 3

Example of key/value with one value being a variable that eval to array:

const y = [3,4];
const x = {"a":19, "b":20, "c":y}; // the y is array
console.log( x["c"][0] ); // prints 3

The syntax for accessing elements can be chained.

// syntax for accesing array/hash can be chained
console.log(
 {"a":19, "b":20, "c":[3,4]}["c"][0]
);
 // prints 3

Following is another example of JavaScript object. This is a JSON format.

// JSON format is basically nested js objects
const myStructure = {
  name: {
    first: "Cat",
    last: "bird"
  },
  age: 19,
  hobbies: [ "shopping", "dancing" ]
};

JSON is essentially a (nested) JavaScript object (including array) where the leaf values are string or number.

Object and Methods

Remember, property names are string type or symbol type. [see JS: Property Key]

Remember, property values can be any type, including any object. (function and array are both objects) [see JS: Object Type]

Define Method

A method is just a property that has value of function.

j = {};                             // create a object
j.m = function (x) {return x + 1;}; // create a method named m

// calling the method
const y = j.m(3);

console.log(y);                 // prints 4

ThisBinding

In JavaScript, when a function is called, it has a associated value called “ThisBinding”.

In function body, the “ThisBinding” is represented by the keyword this.

The purpose of “ThisBinding” is to allow function to implicitly work with a object. (without actually declare a parameter in definition and passing a argument in call.)

When a function is called as a method in the form obj.f(), the value of “thisBinding” is the object obj.

// create a object, with one property p1
const obj = {"p1":3};

// make property p2 to be a function, which simply return 「this」
obj.p2 = function () { return this; };

// show obj
console.log( obj );               // { p1: 3, p2: [Function] }

console.log( obj === obj.p2() );   // true

// returns true because p2 is a function that returns 「this」, which is obj

How this keyword gets its value depends on many things. For detail, see JS: “this” Binding

JavaScript Object Model

JavaScript object model is very different from Java, Python, Ruby.

For detail, see: JS: Object Overview

Browser Console Object Syntax Error?

browser console js object syntax error 20161027
Common error when using brower console to evaluate a JavaScript object literal expression.

see JS: Browser JS Console Object Syntax Error

JavaScript Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

JavaScript in Depth

Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics

Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment

String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

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

Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Create Object
  6. Object Literal Expr
  7. Create Object with Parent X
  8. Get/Set Parent
  9. Show Prototype Chain
  10. Prevent Adding Property
  11. Clone Object
  12. Test Object Equality
  13. Add Method to Prototype

Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”

Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function

Misc

  1. Set Object
  2. Map Object
  3. Try Catch Throw Finally
  4. Import/Export
  5. Promise
  6. Proxy
  7. ES2015 Features
  8. How to Convert ES5 to ES2015
  9. Style Guide
  10. Semicolon Rules
  11. Exclamation Before Function
  12. How to Determine Strict Mode?
  13. x.y.z Associativity
  14. Function Chain
  15. Random Number, Range, Integer, Element
  16. Timing JS Code
  17. Range Function for Array
  18. Random Array Element, Randomize Array
  19. Tagged Template String
  20. String to Number
  21. Format Number

Object Reference

  1. the Global Object
  2. Object 🙼 Object.prototype
  3. Array 🙼 Array.prototype
  4. Function 🙼 Function.prototype
  5. String 🙼 String.prototype
  6. RegExp 🙼 RegExp.prototype 🙼 RegExp Syntax
  7. Date 🙼 Date.prototype
  8. Set ⭐🙼 Set.prototype
  9. Map ⭐🙼 Map.prototype
  10. JSON
  11. Math
  12. Reflect
  13. Symbol ⭐🙼 Symbol.prototype
  14. Number 🙼 Number.prototype
  15. Boolean 🙼 Boolean.prototype

DOM How-To

  1. Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. Remove Element's Attribute Value
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. Navigate DOM Tree

DOM Overview

  1. Browser Window Object, Document Object Model
  2. Intro to Event-Based Programing
  3. JavaScript Load Order
  4. What is Live Object
  5. NodeList vs HTMLCollection
  6. DOM: Whitespace Nodes

Basic DOM Methods

  1. Basic DOM Methods
  2. Node Type, Name, Value
  3. Navigate DOM Tree

HTML Form

  1. HTML Form
  2. Visit URL in a New Window
  3. Instant Field Validation
  4. Input Field Validation
  5. HTML: Input Range Slider

DOM How To

  1. Encode URL, Escape String
  2. Browser Info, Navigator Object
  3. Get URL (window.location)
  4. Web Cookies
  5. Web Storage
  6. Find Window Width
  7. Find Element Width
  8. WebSocket

Web Scripting Examples

  1. Disable Right Click
  2. document.write
  3. Image Rollover
  4. Pop-up New Window
  5. Digital Clock
  6. Stopwatch
  7. Fade a Element
  8. Fade a Element Using CSS Transition
  9. Shake Element
  10. How to Create Tooltip
  11. Falling Snow Effect
  12. JavaScript: Floating Box Following Scroll

DOM Misc

  1. Value of “this” in Event Handler
  2. Event Delegation
  3. Get Current Script Tag
  4. insertAfter Element
  5. Randomize List
  6. create Document Fragment
  7. innerHTML, nodeValue, textContent, innerText?

jQuery

  1. jQuery Basics
  2. jQuery() vs querySelectorAll()
  3. Write JQuery Plugin

node.js