JavaScript

What one should know about the basic of JavaScript Objects!

  
  • Favourite
Average Star Rating is 3.2 from the Total 10 Ratings


Let's talk about JavaScript Object. In JavaScript, objects are Ruler. If you understand objects, then you almost understand JavaScript. That’s because, in JavaScript, almost "everything" is an object. These are called “Standard Built-in Objects”. If you are interested to know more about them then head onto MDN (Mozilla-Developer-Network) documentation at: MDN Website. But here, I will talk about how you also can create your own Objects. So what is an Object anyways? Well, you have already learned that JavaScript variables are containers for data values. Objects are variables too. But objects can contain many values, bit like arrays (which also can contains many values). The basic difference is while array uses numeric indexing (starting from 0) to maintain the order and to identify the position of the values in the array, on the other hand, in object, we can use a key, a given name, to maintain and to identify each value in the object. For object, this actually helps identifying a value more humanly-way over numerical indexing. Both the arrays and objects have their own use, reasons and strength, we just use either of them or even mix them when we need for a particular case. In JavaScript, you can create an object in a number of different ways, here I am going to discuss two most common ways. One with Object Literal notation and another one is with an Object Constructor function.

 

Note: In all of these examples I will be using console to print the output, so while testing the code please open your console by right-clicking on the page and select inspect (I prefer Google Chrome browser ) 

 

Using Object Literal notation (My favourite): 

 

Let's create an object called student: This student object will have three properties called name, age, subject and two methods namely currentlyLearning() and showAge(); Here, we are just creating this object for demonstration purpose only.

var student = {
    name : "Sam Smith", 
    age: 25,
    subject : "JavaScript",
    currentlyLearning: function(){
        return this.name + " is learning " + this.subject;
    }, 
    showAge : function(){
        return this.name + " is " + this.age + " year's old!";
    } 
};

 

Now if we want to print the individual property and method of this object manually then we can do the following.

 

// You can access object properties in two ways 
console.log(student.name); 
// or
console.log(student['name']);

 // Let's print currentlyLearning method
console.log(student.currentlyLearning());

Output: 

Sam Smith
Sam Smith
Sam Smith is learning JavaScript

 

Hint: If you access a method without the () parentheses, it will return the function definition, (the body of the function) so don't forget it: consider this example:

console.log(student.currentlyLearning);

Output:

ƒ (){
    return this.name + " is learning " + this.subject;
}

 

But what if we want to print all the properties and methods in one go? Well, JavaScript provides a loop called for-in loop. 

var property = "", method  = "";
var propertyCounter = 0, methodCounter = 0;
console.log("-----------Printing the datatype of the each member of the object-----------");
console.log("------------------------------------------------------------------");
for(var key in student){
    console.log(key+" : "+typeof student[key]);
   if(typeof student[key] == 'function'){
      methodCounter++;
      method += "nMethods- "+ methodCounter +" : " +key + "() : "+student[key]() +   "n";
   } else{
      propertyCounter++;
      property += "Property- "+ propertyCounter +" : " + toTitleCase(key) + " : " +student[key] +   "n";
   }
}
console.log("n-----------Printing the object details -----------");
console.log("------------------------------------------------------------------n");
console.log(property+method)

function toTitleCase(str){
   return str.charAt(0).toUpperCase()+ str.substr(1).toLowerCase()
}

 

Note: Did you notice on line number 7 and 9 of the above example,  using typeof operator how I had to tell the loop to check if the member of the object is a type of function, and if so, to add additional () parentheses student[key]() to call the function, otherwise, it will print the function definition (function body) instead. Also, on line 12 I have used a custom built function called toTitleCase(), this function will be used to convert our object-keys to Title case from lower case, just for displaying purpose. The definition of this function can be found on Line 19 to 21.

Output:

-----Printing the datatype of the each member of the object-------
------------------------------------------------------------------
name : string
age : number
subject : string
currentlyLearning : function
showAge : function

-----------Printing the object details -----------
--------------------------------------------------

Property- 1 : Name : Sam Smith
Property- 2 : Age : 25
Property- 3 : Subject : JavaScript

Methods- 1 : currentlyLearning() : Sam Smith is learning JavaScript

Methods- 2 : showAge() : Sam Smith is 25 year's old!

 

There is another way to loop through objects. This case, first to convert the object into an array. Then, you loop through the array. You can convert an object into an array with three methods:

Method-1:

console.log("nn---Another better way to loop through objects----");
console.log("-----------------------------------------------");
// Object.keys creates an array that contains the properties of an object. 
console.log("nn---Object.keys(student) creates an array that contains the properties/keys of an object--");
var keys = Object.keys(student)
console.log(keys) 

Output:

["name", "age", "subject", "currentlyLearning", "showAge"]

 

Method-2:

//Object.values creates an array that contains the values of every property in an object
console.log("nn--Object.values(student) creates an array with the values of every property in an object--");
var values = Object.values(student)
console.log(values) 

Output:

["Sam Smith", 25, "JavaScript", ƒ, ƒ]

 

Method-3:

//Object.entries creates an array of arrays. Each inner array has two item. 
//The first item is the property; the second item is the value.
console.log("nn--Object.entries(student) creates an array of arrays. Each inner array has two item--");
var entries = Object.entries(student)
console.log(entries) 

Output:

["name", "Sam Smith"]
["age", 25]
["subject", "JavaScript"]
["currentlyLearning", ƒ]
["showAge", ƒ]

 

Now that you have learned about Object Literal Notation to create an object (The best one out of two for a few reasons ), let's see how can we do the same using  Object Constructors function. 

 

Using Object Constructors function:

 

The examples above of Object Literal are limited. They only create single objects. Sometimes we need a "Blueprint" (Classes) for creating many objects of the same "type". The way to create an "object type", is to use an object constructor function.

Hint: It is considered a good practice to name constructor functions with an upper-case first letter.

Example: 

function Student(name, age, subject) {
    this.name = name;
    this.age = age;
    this.subject = subject,
    this.currentlyLearning = function(){
        return this.name + " is learning " + this.subject;
    }, 
    this.showAge = function(){
        return this.name + " is " + this.age + " year's old!";
    }
  }

In the example above, function Student() is an object constructor function. Objects of the same type are created by calling the constructor function with the new keyword, let's now create two instances of Student Object Type.

  var sam = new Student("Sam Smith", 25, "JavaScript");
  var lucy = new Student("Lucy Smith", 30, "PHP");

 

Now let's print one of these Object Instance's details using the previously used for-in loop.

var property = "", method  = "";
var propertyCounter = 0, methodCounter = 0;
  console.log("nn-----------Object Constructors function-----------");
  console.log("-----Printing the datatype of the each member of the object-----------");
  console.log("------------------------------------------------------------------");
  for(var key in lucy){
     console.log(key+" : "+typeof lucy[key]);
     if(typeof lucy[key] == 'function'){
        methodCounter++;
        method += "nMethods- "+ methodCounter +" : " +key + "() : "+lucy[key]() +   "n";
     } else{
        propertyCounter++;
        property += "Property- "+ propertyCounter +" : " + toTitleCase(key) + " : " +lucy[key] +   "n";
     }
  }

console.log("n-----------Printing the object details -----------");
console.log("------------------------------------------------------------------n");
console.log(property+method)

function toTitleCase(str){
   return str.charAt(0).toUpperCase()+ str.substr(1).toLowerCase()
}

Output:

-----Printing the datatype of the each member of the object-------
------------------------------------------------------------------
name : string
age : number
subject : string
currentlyLearning : function
showAge : function

-----------Printing the object details -----------
--------------------------------------------------

Property- 1 : Name : Lucy Smith
Property- 2 : Age : 30
Property- 3 : Subject : PHP

Methods- 1 : currentlyLearning() : Lucy Smith is learning PHP

Methods- 2 : showAge() : Lucy Smith is 30 year's old!

 

Final Say: Though technically they do the same thing, however, Object Literal Notation technique takes less space in the source code. It's clearly recognisable as to what is happening. In practice, there's never a reason to use new Object rather than {}. Both Object Literals and Object Constructors function (Instance Objects) have their place and purpose in JavaScript. The power of Object Literals is in their lightweight syntax, ease of use. Object literals enable us to write code that supports lots of features yet still provide a relatively straightforward process for implementers of our code.

 

 

References : 

  • https://www.w3schools.com/jsref/jsref_forin.asp
  • https://www.w3schools.com/js/js_objects.asp
  • https://www.w3schools.com/js/js_object_definition.asp
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
  • https://www.dyn-web.com/tutorials/object-literal/
  • https://stackoverflow.com/questions/4597926/what-is-the-difference-between-new-object-and-object-literal-notation
  • https://blog.kevinchisholm.com/javascript/difference-between-object-literal-and-instance-object/
  • https://zellwk.com/blog/looping-through-js-objects/

 

 


Be the first to make a comment!