JavaScripts Objects – The Basics

Note: This post is work-in-progress learning-note and still in active development and updated regularly.

In JavaScript objects are everything. The object, classified as one of the data types, refers as named container to store more complex data (values). To quote objects from MDN:

Object refers to a data structure containing data and instructions for working with the data. Objects sometimes refer to real-world things, for example a car or map object in a racing game. JavaScript, Java, C++, Python, and Ruby are examples of object-oriented programming languages.  MDN – Object

In other words, objects are more complex variables containing values enclosed in curly braces ( { }), and optional list of properties represented in key:value pairs, separated by commas. The object property is a string (often called a “property name”) used to describe object, and values of the object properties could hold primitive (string, number, Boolean, null, undefined & symbol)  or object (more complex) data types.

JS objects are like objects in real life (eg. car, laptop, book etc).  For example a laptop has properties like make, model, color, weight and some methods like start and stop. All laptops have same properties but their values vary from laptop to laptop. Likewise all laptops have same methods but the are performed at different times.

In this learning-note post, some basic features of objects: syntax, creating objects with literals, properties & methods, assessing object properties & methods will be discussed. Other more advanced features are discussed in JavaScript Objects – Prototypes, Inheritance & Classes.

Object Syntax

An simple empty object can be created using literal notation or new.object() as follows:

// Object syntax
let car = {};  // "object literal" syntax
let car = new Object(); // "object constructor" syntax

//initialize object with properties
let car = {make:"Toyota", model:"Corolla", year:2016, color:"blue"};

In the example above, car is the name of an object (line 2) with no properties. We can define its property by adding key:value pairs within the { ..} separated by commas (line 6).

An object variable can hold different data types. Lets add some properties to the car object and assign with different data types:

//Initializing primitive data types
let car = {
  make : 'Toyota', //string
  year : 2016, // number
  electric : false, // Boolean
  '' : null, //null
  other : undefined, //undefined
  engine : { // object
        cylinders : 4,
        size : 2.2}
};

In the example above, the car object was described with six properties [make, year, electric, a space ( " " ), other & and engine (an object variable] and assigned value with string, number, Boolean, null, undefined & object data types.

Property Names

Similar to JS variables, property names must be string or anything that can be converted to string. It may contain alphanumeric characters including underscore ( "_" ), and dollar sign ( "$" ) but does not start with a number. A string does not have to be valid identifier and it may contain any value including "2TWO", “!Bang!“, or a space ( "  " ). Additional information in computed property names is discussed on MDN.

Creating New Objects

MDN lists three ways to create new objects in JavaScript. In this post, we will create new objects using object literal & object constructor. New Objects creation with constructor function & object.create method is discussed only briefly here. This section will be discussed in JavaScript Objects – Prototypes, Inheritance & Classes.

1. Using Object Initializers

JS objects can be created using Object Initiazers also called as literal notation. This is easy and quick way to create a new object just by adding comma separated property:value pairs in { }. In the example below, we will create an object myCar with five properties (keys), make, mode, year, electric & engine with corresponding values: 'Toyota', 'Camry', 2017, false (a Boolean) and an object { cylinder : 4}. Object property can hold an object as value.

//Create an object
let myCar = {
  make : 'Toyota', 
  model : 'Camry',
  year : 2017, 
  electric : false, // Boolean
  engine : { cylinders : 4 } // object
};
2. Using new Object Constructor

New objects can also be created using new object constructor. In the following example, we will use use previous code and create myCar object (same property:value pairs) using new object constructor.

//Create an object with new keyword
let myCar = new Object ();
  myCar.make = 'Toyota'; 
  myCar.model = 'Camry';
  myCar.year = 2017; 
  myCar.electric = false; // Boolean
  myCar.engine = { cylinders : 4 }; // an object

This example above is exactly same as created with object initializer above. Its syntax is different, each statement is closed with ; and no curly braces { } is needed to create a new object. Objects created with new keyword constructor are known to be slower.

3. Using Constructor Function

Another way to create a new object is using Constructor Function. This is similar to a JS function except that it does not return anything (as function do) and does not create an explicit new object but only defines its properties and methods.

Lets create a object Car object function with three parameters, its make, model and year made. Then we will its owner by adding Person object function with the parameters: name, age and sex.

In the example below, we will define a object Car using function constructor with three properties, make, model, and year of manufacture.

//create and define constructor function
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

In the example we have used this keyword to assign values to the object’s properties based current execution context values (eg. Car) passed to the function.

Tip: There is strong convention to start a constructor function name with a capital letter, making easier to read & recognize..

Now you can create an object called mycar as follows. This statement creates mycar and assigns it the specified values for its properties: mycar.make is the string “Toyota”, mycar.year is the integer 2017, and so on.

//create object myCar
let mycar = new Car('Toyota', 'Camry', 2017);

We can create any number of Car objects by calls to new. The new keyword instruct the browser to create a new object instance, followed by the function name with its required parameters contained in parentheses, and the result is stored in a variable — very similar to how a standard function is called.

In the example below we create two new Car objects robscar & lucyscar and pass specific values for each car properties.

//define new car objects
let robscar = new Car('Nissan', '300ZX', 1992);
let lucyscar = new Car('Mazda', 'Miata', 1990);

An object can have a property that is itself another object. For example, suppose we define an object called Person as follows with the properties: name, age and sex as done before and assign values to the object’s properties using this keyword.

//create owner object
function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

and then instantiate two new Person objects as follows:

//add new persons
let rob = new Person('Rob Johnson', 26, 'M');
let lucy = new Person('Lucy Jonson', 19, 'F');

Next we would like to add car owner property to our Car object. To add additional properties to an already define object, it has to be done redefining our original Car object.

Lets rewrite the definition of Car to include an owner property that takes a Person object, as follows:

//add owner property
function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

To instantiate the new objects, you then use the following:

// add the following 
let car1 = new Car('Ford', 'Fusion', 2016, rob);
let car2 = new Car('Honda', 'Civic', 2017, lucy);

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rob and lucy as the arguments for the owners.

If we want to find out the name of the owner of car2, we can access the following property:

// invoke car2 owner
car2.owner.name
//OUTPUT
..

Likewise, we can add a property to existing (predefined) object. Lucy’s car is red in color and Rob’s car is creamy color. Lets say we want to add color property to car2 (lucy’s car), it can be added as follows:

//add property to existing object
car2.color = 'red';

//OUTPUT
...

In the above example, we added color property to Lucy’s car car2 only and does not define color of other cars (rob and mycar). To add this property to all cars, it should be done by rewriting our Car object as done for owner property addition.

4. Using object.create Method

JavaScript objects can be created using  the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create" target="_blank" rel="noopener">object.create()</a> method. In the following example, we expand Car object using object.create() method. Because this type of creating new JavaScript object is prototype based and it will be discussed in more detail a separate section in JavaScript Objects – Prototypes, Inheritance & Classes.

// Car properties and method encapsulation (1)
let Car = {
  type: 'Truck', // Default value of properties
  carType: function() {  // Method which will display type of Car
    console.log(this.type);
  }
};
// Create new car type called car1 (2)
let car1 = Object.create(Car);
car1.carType();
//OUTPUT
Truck

// Create new Car type called passengerCar
let passengerCar = Object.create(Car);
passengerCar.type = 'Ford Fusion';
passengerCar.carType();
//OUTPUT
Ford Fusion

In the above MDN modified example a Car object template is created (1) using object.create() method and assigned a default string value 'Truck‘ to our car type property. Now we can create a new objects car1 (2) and passegerCar (3) as shown above.

Accessing an Object Property

This is also referred as property accessors. Object property can be accessed by the following two ways:

  • Dot notation. Object properties with valid identifier can be assessed with a dot notation.
  • Bracket notation[ ]. Property name that is not a valid JS identifier (that has a space or a hyphen, or that starts with a number or multi-word string) can only be accessed using the square bracket notation.

Lets revisit our myCar object and modify its property names to include some strings as follows:

//Create an object
let myCar = {
  make : 'Toyota', 
  model : 'Camry',
  "year made" : 2017, 
  " " : null,
  electric : false, // Boolean
  engine : { cylinders : 4 } // object
};

//object call
myCar:

//OUTPUT
{make: "Toyota", model: "Camry", year made: 2017, " ": null, electric: false, …}

To access the object, we call object name myCar (line 12) and we get the entire object values we passed on (properties:values pairs) in a string form in the output(line 15). The output format may varies depending upon web browser used.

Now if we want access individual property value, we have to use

Accessing property value with . notation: Lets access some of our object property using dot ( . ) notation.

//property access syntax with dot
objectName.propertyName

//Access property value with dot (1)
myCar.model;  
//OUTPUT
"Camry" 

//access (2)
myCar.engine;  
 //OUTPUT
{cylinders: 4}

//access string 
myCar." ";  
//OUTPUT
SyntaxError: Unexpected string

In the example above, property value of model and engine were accessed using . notation as myCar.model (line 7) and myCar.egine (line 12). If we try to access the value of empty string, it will throw us SyntaxError message (line 17).

Accessing property value with [ ] brackets: Any property name that is not a valid JS identifier [eg, with space " "  or a hyphen ( _ ), or that starts with a number ( 6Teen ) ] can only be accessed using the square bracket notation. This is also useful when property names are dynamically determined.

//property access syntax with bracket
objectName["propertyName"]

//Access
myCar[" "];
//OUTPUT
null

//access
myCar["year made"];
//OUTPUT
2017

//acess 
myCar["make"];
//OUTPUT
Toyota

In the example above, when properties with empty string ("  ") and multi-world names were accessed using square bracket [ ] (line 5 & 10), we got expected values (line 7 and 12).

Tip: Multi-worded properties must be enclosed in quotes ( "  " ). Bracket notation [  ] works for any string. Additional case examples are documented in The Modern JavaScript Tutorial.

Properties & Methods

JS methods are actions that can be performed on an object. These actions are performed by using function as an object property. In other words, a function that is property value of an object is called its method. These functions are defined as normal function but as property value of an object.

Adding Method to an Object

Lets revisit our myCar object and modify its properties to include a reminder method. This can be illustrated in two steps: first, create a standalone function reminder(), and then add this function as a myCar object property.

//Initialize function 
function reminder() { 
  return `Bring my Toyota to garage for check up!`;  
} 
//invoke function
reminder();
//OUTPUT
Bring my Toyota to garage for check up!

In the example above, we created reminder() function (line 2) with some return value. Now as in a normal function, we can access the value of reminder() with expected value (line 8).

Now lets add the function reminder() to our myCar object as follows:

// add function as property of myCar
let myCar = { 
 make : 'Toyota', 
 model : 'Camry', 
 reminder : function() { 
  return `Bring my ${this.make} to garage for check up!`; 
  }, 
};

In the example above, we added a reminder() that we created previously as property of myCar object (line 5)

Tip: The this is keyword and not a variable. Its value can’t be changed.

Accessing Object Method

A object method can be accessed using syntax shown below (line 2). For example, string value of reminder() method is returned (line 7) by calling myCar.reminder() as shown in (line 5).

//Syntax accessing Object methods
objectName.methodName()

//access reminder property value
myCar.reminder();
//OUTPUT
“Bring my Toyota to garage for check up!”

// accessing object myCar
myCar;
//OUTPUT
{ make: "Toyota", model: "Camry", reminder: reminder() }

Object string value of object property is returned including the reminder() method.

Tip: If a property method is accessed without (), it will return the function definition.

The this Keyword in Object Methods

The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" target="_blank" rel="noopener">this</a> keyword behaves differently in JS. To quote from MDN “when a function is called as a method of an object, its this is set to the object the method is called on“.

//initialize object
let myCar = {
  make: 'Toyota',
   makeFunction: function() {
    return this.make;
  },
};

//object call
console.log(myCar.makeFunction());
//OUTPUT
Toyota

In the example above, when myCar.makeFunction() was invoked (line 10), the this (line5) refers to object myCar in line 2. In other words, the value of this is object name before the dot (i.e. myCar.make). What it means is, if we replace this in line 4 with myCar object as return myCar.make; we still get the same ‘Toyota‘ output.

Additional use cases of this keyword are discussed in JavaScript Objects – Prototypes, Inheritance & Classes.

Modifying Object Properties

JS object properties can be modified using dot and bracket notation. Object properties can be added or deleted, modified existing property value by re-assigning a new property value. Lets examine this features below using our simplified myCar object example:

// initialize an object
let myCar = {
  make : 'Toyota',
  year : 2017,
  reminder : function() {
   return `Bring ${this.make} to dealer for checkup.`;
 },
};
//access object
myCar;

//OUTPUT
{ make: "Toyota", year: 2017, reminder: reminder() }
Adding Properties

Now lets add two properties (model, electric or not) to the myCar object using dot and bracket notation.

//add properties to objects
myCar.model = "Corolla";
myCar["electric"] = false; //Boolean

//OUTPUT
Corolla
false

//access myCar
myCar;
//OUTPUT
{ make:"Toyota", year:2017, reminder:reminder(), model:"Corolla", electric:false }

In the example above, we added two properties to myCar object using dot & bracket notation (line 2 and 3) and assigned properties value of "Corolla” and false ( a Boolean data type) and got expected outputs (line 6 and 7). This can be confirmed by accessing myCar object (line 10) with expected object value (line 12) showing our two newly added property:value combinations.

Removing Object Properties

An object property can be removed by using a delete operator. Using delete operator lets remove electric property from myCar object:

//delete electric from myCar
delete myCar.electric;
//OUTPUT
true

//call myCar object to verify
myCar;
//OUTPUT
{ make: "Toyota", year: 2017, reminder: reminder(), model: "Corolla" }

In the example above, we deleted electric property from our myCar object using delete operator as delete myCar.electric (line 2) with expected output true (for successful execution ; false if not successful) in line 4. In line 7, it is confirmed that myCar object property electric is successfully deleted from the object.

Duplicating a Property Name

When we create property name of any object, they should unique and different, or else if we use the same name, the second one will overwrite the first.

//using var
var a = {
  x: 1, 
  x: 2
};
//OUTPUT
console.log(a); // => {x: 2}

//Using let 
let myCar = {
  make : 'Toyota', 
  make : 'Honda'
};
//OUTPUT
console.log(myCar); // => { make: "Honda" }

In the example above, when we use the same property name to initialize an object (lines 2 & 12) the second property name overwrites the first value (line 7 & 15).

Modifying property value

A property value can be modified reassigning a new property value to an existing property, as shown below:

//Initialize an Object
let myCar = {
  model : 'Toyota',
  year : 2017,
};
//access an object
myCar;
//OUTPUT
{model: "Toyota", year: 2017}

//re-assign a new property value
myCar.model = 'Ford';
//access object
myCar;
//OUTPUT
{model: "Ford", year: 2017}

In the example above, myCar object property model has been assigned a string value 'Toyota' (line 3).  We re-assigned its value with a new string 'Ford' (line 12) and value re-assignment is confirmed in output (line 16).

Adding Methods to Object

Earlier we looked at adding methods to object. Lets try again adding a simple reminder methods for oil change to our myCar object example below. As expected we get an output confirmation (line 13).

//add method to an object 
myCar.reminder = function() {
  return `Bring ${this.model} for oil change.`;
},
//Call object myCar
myCar; // (1)
//OUTPUT
{model: "Toyota", year: 2017, reminder: ƒ}

//call reminder property 
myCar["reminder"](); 
//OUTPUT
"Bring Toyota for oil change."

Object for ..in Loop

JS has a special for..in loop statement  to walk-over (iterate) enumerable properties of an object. Enumerable properties show up in for…in loops (once for each property) unless the property’s name is Symbol.

According to MDN, Enumerable properties are those properties whose internal [[Enumerable]] flag is set to true, which is the default for properties created via simple assignment or via a property initializer”.

Lets examine this feature in myCar object example below:

//Create an object
let myCar = {
  make : 'Toyota', 
  model : 'Camry',
  year : 2017, 
  electric : false, // Boolean
};
//logout ..
for(let key in myCar) {
  // keys
  console.log( key );  // 
}
//OUTPUT
make
model
year
electric

//log out .. 
for(let key in myCar) {
 // values for the keys
 console.log( myCar[key] );//
}
//OUTPUT
Toyota
Camry
2017
false

Tip: The iteration occurs in arbitrary fashion, not in the same order they were added. Integer property are sorted in  ascending order other properties occur in the order of creation. This must be use with caution.

Wrapping Up

In this section, we looked at JavaScript Object, it syntax, methods of creating new objects, accessing and modifying object properties, property values. In the next section JavaScript Objects – Prototypes, Inheritance & Classes we will deep dive into prototypes, inheritance, classes and object oriented programming.

NEXT: JavaScript Objects – Prototypes, Inheritance & Classes

Resources & Further Reading

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.