The Definitive Guide to the JavaScript Objects9 min read

Like arrays, objects are used to store data, but instead of storing data in a single variable and you can access its elements by index. Object grants us the collection of properties, and a property is an association between a name (or key) and a value, also called key-value pair. Inside each property’s value, you can also pass into it a function, which called a method.

Overview

If you have learned some other programming languages before reading this article, you can see also that these languages such as Python, Java or C# they all support a type of programming named Object-oriented-programming (OOP) and object is the indispensable part of this technique. In JavaScript, like the name itself, object in JavaScript like the object in real life. For example, A bird has the wings with the color brown, a bird is a real-world object. With this tangible value, we can consider a wing of the bird is its property and the color is the value of its property.

Creating a new object

Similar to create arrays, you can create an Object by using Object literal, Object constructor but also the function constructor and the Object.create() method can be used.

Object literal

var object = {
  foo: 'bar',
  age: 42,
  baz: {myProp: 12}
}

Let’s consider the example above, we’ve created an object by using { } (curly brackets) and assign it to a variable named object. Inside this object, we have key-value pair, in each element, before the colon is the property name and after that is its value. As you can see in baz‘s property, its value is myProp: 12 but myProp is also consider property and 12 is its value because it’s enclosed between the curly brackets. And the point is, inside an object, you can store various data of different types. In this case, the object contains another object called the nested object. Remember we put the comma after each value, not semicolon.

Accessing property’s value

There are two ways to access the property’s value in an Object.

Using simple dot-notation

the first one is simple dot-notation: objectName.propertyName

var countries = {
    Asia: ["India", "China", "Vietnam", "Sri Lanka"],
    Europe: ["Switzerland, "Sweden", "UK", "Netherland"],
    America: ["the US", "Canada"],
    Australia: ["Australia", "New Zealand"],
    Africa: ["South Africa", "Nigeria"]  
}
PropertyProperty Value
Asia[“India”, “China”, “Vietnam”, “Sri Lanka”]
Europe[“Switzerland”, “Sweden”, “UK”, “Netherland”]
America[“the US”, “Canada”]
Australia[“Australia”, “New Zealand”]
Africa[“South Africa”, “Nigeria”]

We’ve just defined an object countries inside it is the key-value pair, and remember, the value of property inside an object can be anything, such as number, function, string, object, etc…In this case, is an array with a list of countries in it.

If we want to access the countries from Europe, simple we use dot notation like this:

countries.Europe
// expected output: ["Switzerland", "Sweden", "UK", "Netherland"]

What happens if we want to access a property that doesn’t exist:

countries.Antarctica // undefined
Using Bracket Notation

Similar to simple dot-notation, you can access the property’s value by using ObjectName[ObjectPropertyName]

countries["Asia"];
// expected output: ["India", "China", "Vietnam", "Sri Lanka"]

When using bracket-notation, inside the bracket, the property should be wrapped into a double quotes, otherwise it will return an error if it is not a function.

Object constructor

var myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;

Similar to array, we create an object constructor by using new keyword and followed Object().

  • The first line of this code above has the duty to create a new object constructor and assign it to myCar value.
  • The second line to the fourth is using dot notation to access the property and assign its value. (We’ll talk about how to access property in an object below).

Rewrite, we have the object like this:

var myCar = {
 make: "Ford",
 model: "Mustang",
 year: 1969
}
myCar
// expected output: {make: "Ford", model: "Mustang", year: 1969}

When you want to call an object, this simple you type its name to the console. However, remember this is an object, not a function. So if you call an object like object above in this way, you will receive the error something like this:

var myCar = {
 make: "Ford",
 model: "Mustang",
 year: 1969
}
myCar()
VM534:6 Uncaught TypeError: myCar is not a function
    at <anonymous>:6:1

Constructor Function

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

To creating an object, you can also use function constructor to handle that, which means when you define a function with its parameters, those will consider as a property of the object if you passed in this function some argument. For example, if you want to create an object called VietNamWar and its property like countryA, countryB and end, you should try something like this:

function VietNamWar(countryA, countryB, end){
         this.countryA = countryA;
         this.countryB = countryB;
         this.end = end;
}

Notice the use of this to assign values to the object’s properties based on the values passed to the function. (We’ll talk more about the this keyword in the later articles).

Now simple you can create an object as follow: var war = VietNamWar("the US", "Vietnam", 1975)

This statement creates a new variable war and assign it to the new object, so the first argument is the first property, war.countryA = "the US", war.countryB = "Vietnam", war.end = 1975, and so on...

function VietNamWar(countryA, countryB, end){
         this.countryA = countryA;
         this.countryB = countryB;
         this.end = end;
}
var war = new VietNamWar("the US", "Vietnam", 1975);
war // call object
/* expected result: {countryA: "the US", countryB: "Vietnam", end: 1975} */

Remember, function constructor distinct with regular function because of its first character when you define a function name. It’s capitalized, which regular function should not.

Regular function:

function regularFunction(){
// do something
}

Function constructor:

function ConstructorFunction(){
// do something 
}

Using Object.create method

Another way to create an object is using Object.create method. This method comes in handy when you don’t have to create a constructor function because it allows you to choose the prototype object for the object you want to create.

var Contries = {
  type: 'Developing', // Default value of properties
  displayType: function() { 
    console.log(this.type);
  }
};

// Create new country1 type called country2
var Country1 = Object.create(Countries);
Country1.displayType(); // Output: Developing

var Country2 = Object.create(Countries);
Country2.type = 'Developed';
Contry2.displayType(); // Output: Developed

Manipulating Object

Method

Inside the property of an object, we can store various type of values, such as a function, you can access the method’s value by calling its name:

var greeting = {
    bar: function() { // method bar
        alert("Hello, I'm Mr. Puppybutthole");
    }  
}
greeting.bar()

method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined as the way normal functions are defined, except that they have to be assigned as the property of an object.

var obj = {
  foo: function() { // method (foo)
    // do something
  },
  bar: function() { // also method (bar)
    // do something
  }
};

Generator Function

The generator function can use shorthand syntax, which means it more readable and concisely. The main characteristic of this function to the others that it has * (asterisk) after the function keyword function *. The result of the generator function will return a generator object.

function* generator(i) {
  yield i;
  yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value);
// expected output: 10

console.log(gen.next().value);
// expected output: 20

var obj2 = {
  g: function* () {
    var index = 0;
    while (true)
      yield index++;
  }
};
// The same object using shorthand syntax
var obj2 = { 
  * g() {
    var index = 0;
    while (true)
      yield index++;
  }
};

var it = obj2.g();
console.log(it.next().value); // 0
console.log(it.next().value); // 1

Loop in Objects

In order to loop through Object in JavaScript, we use for...in loop to all the enumerable properties of an object:

var countries = {
    Asia: ["India", "China", "Vietnam", "Sri Lanka"],
    Europe: ["Switzerland, "Sweden", "UK", "Netherland"],
    America: ["the US", "Canada"],
    Australia: ["Australia", "New Zealand"],
    Africa: ["South Africa", "Nigeria"]  
}
for(let i in countries){
   console.log(i)
}
/* Expected output: 
Asia
Europe
America
Australia
Africa
*/

Pretend that you want to loop over the object and want to get the first element of each property, you can do something like this:

for(let i in countries){
console.log(countries[i][0])
}
/* expected output:
India
Switzerland
the US
Australia
South Africa
*/

If you want to print out an object’s property’s and value’s name at the same time, with for in loop:

var obj = {a: 1, b: 2, c: 3};
    
for (const prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

Object.Prototype.hasOwnPropertyName

Like it name, this methods will return whether true or false based on the whether this property is existed in object or not. Return true if the given object has own this property, otherwise false.

var object1 = new Object(); // object constructor
object1.property1 = 69;
object1.property2 = 96;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

console.log(object1.hasOwnProperty('property2'));
// expected output: true

console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false

Object​.get​OwnProperty​Names()

This method all the property found in the given object, including non-enumerable properties except for those which use Symbol.

Syntax:

Object.getOwnPropertyNames(obj)

var object1 = {
a: 6,
b: 9,
c: 69,
d: 96,
e: 7777
}
console.log(Object.getOwnPropertyNames(object1))
// output: a, b, c, d, e

Delete object’s properties

You can delete a property of an object by using delete operator:

var objectX = {
a: 2,
b: 4,
c: 6}
delete objectX.b
console.log(objectX)
/* output: a: 2,
           c: 6
*/
console.log('b' in objectX) // false

Comparing Objects

Remember objects in JavaScript are reference type, if 2 objects are compared together, JavaScript doesn’t compare the value inside each object, but instead it compares the reference of those two objects.

// Two variables, two distinct objects with the same properties
var fruit = {name: 'grape'};
var anotherfruit = {name: 'grape'};

fruit == anotherfruit; // return false
fruit === anotherfruit; // return false

In this example above, because the reference address of two objects never be the same, hence we cannot get the true value when comparing them.

But you can make it returns true if you point assign the address of one object to another:

var fruit = {name: 'grape'};
var anotherfruit = {name: 'grape'};
fruit = anotherfuit;
fruit == anotherfruit; // true;
fruit === anotherfruit; // true;

We just make the fruit address point to the same address as the anotherFruit object, now those two objects are equal.

Also read:

Conclusion

In this article, we’ve learned how to create an object in some ways, these are literal, constructor, and function constructor. Each object has its own property, each property has its values, which we call key-value pairs. You can access the properties’ values by either using dot-notation or bracket notation. Generator functions started with * (asterisk before the function keyword) and always return a generator object. Object.hasOwnProperty() the method will return true if this property exists in the provided object and false if it doesn’t. To get the name of properties, you can use Object.getOwnPropertyNames() method. Comparing objects will always return false due to the reference type. Delete keyword is used to remove the specific property in an object.

Previous Article
Next Article
Every support is much appreciated ❤️

Buy Me a Coffee