JavaScript: the 'new' keyword

Petr Kostelanský | 28 October 2017
In this article we are going to discuss about the 'new' keyword in javascript and it's importance.

 The new keyword ensures two important things:

  • creates new empty object 
  • sets the context of this to that new object

With new keyword

In the first example I will create new object peter by calling constructor function Person with the new keyword:

function Person(firstName, surname){
     this.firstName = firstName;
     this.surname = surname;
};

var peter = new Person("Peter", "Forst");

console.log(peter.firstName + " " + peter.surname); 
// Output: Peter Forst

console.log(window.firstName + " " + window.surname); 
// Output: undefined undefined

So what happend when we called this:

var peter = new Person("Peter", "Forst");

The new object was created and the this context of Person function was set to the new object.

Person function was callled and caused creating properties on object representing by this and set their values.

That new object was assigned to the peter variable.

Without new keyword

Let's look at an example without new keyword:

function Person(firstName, surname){
     this.firstName = firstName;
     this.surname = surname;
};

var peter = Person("Peter", "Forst");

console.log(peter.firstName + " " + peter.surname); 
// Output: TypeError: Cannot read property 'firstName' of undefined

console.log(window.firstName + " " + window.surname); 
// Output: Peter Forst

And what happend when we call Person function without new?

var peter = Person("Peter", "Forst");

Ih this situation the Person function was called and this context was set to the window object. The peter variable is undefined because the Person function is without return and no object is created without the new keyword.

More information about the new keyword you can find on Mozilla Developer Network

Loading ads...