Simplifying Object.assign method in JavaScript

Read full article on the Infragistics blog

“In JavaScript, Object’s assign method copies source object’s own enumerable properties to a target object, and returns that target object “

There are two important keywords in the above sentence:

  1. Enumerable
  2. Own

Before we go ahead and understand purpose of Object.assign, it is essential that we really understand these two words, enumerable properties and own properties.  Let us see them one by one:

A JavaScript object could have either enumerable or non-enumerable properties. However, by default when you create property on an object, it is enumerable.  Enumerable  means you can enumerate through those properties. Let us understand it through code.

 

 

There are two properties in babycat object. By default both are enumerable, hence as the output of for..in loop, you will get both age and name printed.

Now let us change default enumerable behavior of age property using Object.defineProperty method.

 

We have changed enumerable of age property to false, so as output, you will get only color printed. Hence, age is no longer an enumerable property of babycat object.

Another keyword in above sentence is own properties. To understand it, you need to understand object prototype chain. All JavaScript objects are part of a prototype chain, hence can access properties of its prototype’s also.  So, own properties are those properties, which are particular to the object and not from the prototype chain.  Let us understand own properties through code examples,

In above code snippet, there are two objects cat and babycat. In addition, [[Prototype]] property of babycat object is set to cat object. When you print properties of the babycat object using for..in loop, you will find as output age, color, name printed as shown in below image:

What is happening here? Well, JavaScript prints all properties from the prototype chain. However, only age and color are, own properties of babycat object.

As of now, you should have understood own properties and enumerable properties in context of a JavaScript object.   So let us revisit first statement of this post,

“In JavaScript, Object’s assign method copies source object’s own enumerable properties to a target object, and returns that target object “

You should able to infer what exactly above sentence implies.  Consider code below :

 

 

 

 

 

Using Object.assign() method , we are copying cat object own enumerable properties to babycat object. Here, cat object is source and babycat object is target. You will get output printed as below:

The Object.assign() method uses [[Get]] on the source object and [[set]] on the target object and invokes setter and getter to perform the task. Essentially, it assigns properties values from source to target object. It does not create new property in the target object.

As of now you know purpose of the Object.assign() method. Let us examine some variations while copying properties from source object to a target object.

Same Properties in both target and source object

If target object has same properties as of source object, then Object.assign() method will  override target object properties.  To understand it consider code listing below:

 

 

 

 

There is age property in both target object and source object.  While copying properties in target object the Object.assign() method will override target object age property, hence you will get output as shown in the below image :

Read full article on the Infragistics blog

Two Problems of a JavaScript Class

 

Starting ECMA 6, JavaScript has class keyword to create a class. I have written in detail about class here. There is no second question that class simplifies the way object is created, inheritance is implemented etc. JavaScript class has,

  • Constructors
  • Methods
  • Extends etc.

Above features of a class helps to easily write Object Oriented JavaScript. As a developer, you do not need to know complexities of prototype chains, relationship between function constructor and its prototype object, and value of object’s __proto__ properties etc. to write effective Object Oriented JavaScript.  So, class keyword  is good addition to JavaScript language, however it is not gospel perfect. It has some problems, which may restrict you to write full-fledged Object Oriented JavaScript. In this post, I am going to share two such problems. Read along,

No Static Member Properties in class

A static member property is shared by all object instance of the class. JavaScript class does not allow creating it inside the class.

You cannot declare properties directly in the class. You can only have it through class’s constructors, and properties created inside constructor is local to the object instances and not shared by all of them.

Above code will throw error “unexpected identifier”.  There is a work around to create static property using the class prototype.

Now on the instances of Speaker class, you can access static property count.

Therefore, you are able to create a static property, but not without help of understanding of prototype.  In my opinion class should have a way to create static property directly inside the class like a method or constructor.

Object instances does not copy definitions from class

To understand this problem, let us first revise Constructor Invocation Pattern and prototype chain. You have a function constructor Speaker.

Using new operator, you can create object instances,

In this approach, a and b object instances both have their own copy of hello method.  Now if you add a hello method to Speaker.prototype, still a and b object instances will access their own copy of hello method. Consider below code:

Read full article on the Infragistics blog

How to Create Basic Inheritance in JavaScript Constructors

There are four ways to create an object in JavaScript. They are as follows:

  1. Object as literal
  2. Constructor Invocation Pattern
  3. Object.create() method
  4. Using class after ES6

Implementation of Inheritance varies according to the object creation method. In this post, I am going to explain creating inheritance in between a function constructor.

Let’s say you have a function:

If you call the animal function using new operator, an object will be created. This way of object creation is also known as “Constructor Invocation Pattern

Object dog and cat both have their own names and age properties. If you want a property or method to be shared across all objects, add that to the prototype of the function.

Using the JavaScript prototype chain, both dog and cat objects can access the canRun method.

Next, let us create another constructor – human:

At this point in time, human and animal functions do not have any relationship. However, we know that human is also an animal. There are two problems with the human constructor.

  1. It has duplicate codes for name and age initialization. It should use animal constructor for this purpose.
  2. It does not have any link with animal constructor

The above said two problems can be removed by creating inheritance in between animal and human function constructors.

You can solve problem 1 of code duplication by modifying the human function as below:

Now, in human function, we are using the call method to manually pass a current object as a value of ‘this’ in animal function. This approach is also called Indirect Invocation Pattern. Now, an object instance for human can be created as shown below:

So far, we have solved problem 1 of code duplication; however, human function is still not linked to animal function. If you try to call canRun method on h1 object, JavaScript will throw you an error.

You can fix this problem by linking the prototype of the human function with the prototype of the animal function constructor. There are two ways to do that.

  1. Using __proto__
  2. Using Object.create() method

You can link prototype of function constructors using Object.create() as shown below:

You can link prototype of function constructors using __proto__ as shown below:

I would prefer the Object.create() method because__proto__ may not be supported in many browsers. After linking prototypes, in one way, you have created inheritance in between animal and human function constructors. Object instance of human can read all properties of animal function and can execute animal function methods.

Read full article on the Infragistics blog here

What are getters and setters in JavaScript

In JavaScript, you may have heard of getters and setters. Let’s take a look at what these things are.

First, a setter is used to set the value of a property. A setter gets called each time the value of the property is changed. In other words, it executes a function for each time a property used inside the setter function is changed. Take a look at the following code:

image

In the object foo, the setter cal will be called each time the property a is changed. As an output, you will get 13 printed. While creating a setter, you need to follow these rules:

  • A setter name could be either string or number.
  • A setter must have exactly one input parameter.
  • There should be only one setter with the same identifier in an object
  • You can remove a setter using the delete operator

For other examples of a setter, let’s take a look at the following code:

image

For the above code snippet as output, Hello Jason will be printed. You can also add the setter to an existing object using Object.defineProperty. Let’s say that you have an object foo:

image

Now to add a setter for the existing object foo , use Object.defineProperty.

image

Read full article on the Infragistics blog

Objects in JavaScript for .NET developers – Part 1

Read full article on the Infragistics blog

Here are some fun facts for you: JavaScript is not an object oriented language, but almost everything in JavaScript is an object. JavaScript does not have classes, and we can create an object from an object. A function can be used as a constructor, and returns a newly created object. Every object in JavaScript contains a second object called a prototype object.

If you’re coming from a .NET background, the sentences you just read probably don’t make any sense. But these are all true statements about JavaScript. And in this post we will focus on different ways to create objects in JavaScript

  1. Object as literal
  2. Creating an object using the new operator and constructors
  3. Creating an object using the Object.create() static method
Object creation as literal

The simplest way to create an object is by creating an object using the object literal. We can create a simple object as shown in the listing below:

Read full article on the Infragistics blog

How to find index of an item in JavaScript Object Array?

Recently while working I came across a scenario. I had to find index of a particular item on given condition from a JavaScript object array. In this post we will see how to find index of object from JavaScript array of object.

Let us assume we have a JavaScript array as following,


var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];

Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.

We can do that by iterating through the array and comparing value at the given key.


function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {

for (var i = 0; i < arraytosearch.length; i++) {

if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}

You can use the function to find index of a particular element as below,


var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);

In this way you can find index of an element in JavaScript array of object. I hope you find this quick post useful. Thanks for reading.