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
var nn = {"cat":19, "dog":20, "rabbit":25};

Access Property

2 syntax to access property:

// creating a object
var 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:

var 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

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

var 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) returns all property names as a array, then use forEach to loop thru them.

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

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

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

// loop thru object's own properties, for enumarable properties only
    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

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.

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

// loop thru a object's enumerable properties and its inherited enumerable properties
for (var 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, List Properties

Get All Keys of Object

Use the Object.keys(obj) method.

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

var 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:
var 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:

var y = [3,4];
var 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
 {"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
var 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: What's Object?

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
var y = j.m(3);

console.log(y);                 // prints 4


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

In function definition, 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
var 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 System 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. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Tutorial by Example
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally
Like what you read? Buy JavaScript in Depth