The new Keyword in JavaScript

The new Keyword in JavaScript

Get an in-depth understanding of the new keyword in JavaScript and learn how it links with the infamous this keyword

·

5 min read

Most people consider the new keyword has something to do with the class constructor, that it is used to create instances using a class, also known as constructor invocation. For example:

// "Constructor function"
function Article(username) {
  this.username = username;

  this.likeThePost = function () {
    console.log(this.username + " have liked the post");
  };
}

//            👇🏽 the `new` keyword
var article = new Article("You");
article.likeThePost();

NO! The new keyword has nothing to do with the class constructor. It actually defines one of the 4 behaviors of the this keyword in JavaScript.

https://media.giphy.com/media/vXIJJBTkgk932/giphy.gif

Purpose of the new keyword

The new keyword is another way of invoking a function. Its purpose is to invoke a function with a this keyword pointing at a whole new empty object. Consider the following example:

function Article() {
  this.title = "The new Keyword in JavaScript";
  this.whatIsThis = function () {};

  console.log(this);
}

var article = new Article();

// Output:
// Article {
//  title: 'The new Keyword in JavaScript',
//  whatIsThis: [Function (anonymous)]
// }

Now, this could be accomplished by using the call method on a function. The call method will invoke your function with the this keyword pointing at a whole new empty object.

//                       👇🏽 The empty object
console.log(Article.call({}));

// Output:
// {
//  title: 'The new Keyword in JavaScript',
//  whatIsThis: [Function (anonymous)]
// }

Do you see the similarity? 💡 It’s because the new keyword is syntactic sugar for the call method on a function.

https://media.giphy.com/media/l49JThpgIOD24fGxi/giphy.gif

Working of the new keyword

When we use the new keyword to invoke our function i.e. “constructor call”, it does 4 things:

  • Create a brand new empty object
  • Link that object to another object
  • Call the function with the this set to that new object that is created in the first step
  • If the function does not return an object, the new keyword returns the this

Let’s understand these things with an example:

function Article() {
  this.title = "The new Keyword in JavaScript";
}

var article = new Article();

In the first step, it creates a new empty object.

In the second step, it links that newly created empty object to another object i.e. the object that we get when we use the prototype property on the constructor function. In our case, it’s Article.prototype. For example:

Article.prototype.author = "John Doe";

console.log(Article.prototype);
console.log(article.__proto__); // 👈🏼 link

// Output:
// { author: 'John Doe' }
// { author: 'John Doe' }

You’re right! that’s how we get the Prototypal Chain.

In the third step, it invokes the function with the this keyword pointing to that newly created empty object (first step). If you notice then you’ll see that there is explicit binding for the this keyword with our function happening here.

In the last step, if the function does not return anything then the new keyword will return the this context and that’s why in the output we get an “instance”.

console.log(article);

// Output:
// Article { title: 'The new Keyword in JavaScript' }

What if the function returns anything? If the return value is of type object and not null then the new keyword will return that. For example:

// 🔴 When returning an object (not null)

function AnObject() {
  this.description = "The return is an object";
  return { greeting: "Hello World" };
}

var greeting = new AnObject();
console.log(greeting); // { greeting: 'Hello World' }

// 🔴 When returning an object (not null)

function AnObject() {
  this.description = "The return is an object";
  return ["Hello", "World"];
}

var greeting = new AnObject();
console.log(greeting); // [ 'Hello', 'World' ]

// 🔴 When not returning an object

function NotAnObject() {
  this.description = "The return is an object";
  return "Hello World";
}

var greeting = new NotAnObject();
console.log(greeting); // NotAnObject { description: 'The return is an object' }

So, these 4 things will happen if you put the new keyword in front of any function.

function WriteAnArticle() {
  var action = "Typing...";
}

var article = new WriteAnArticle();
console.log(article); // WriteAnArticle {}

https://media.giphy.com/media/HNtEpBViJAeU8/giphy.gif

For PROs Only

The this context can be bonded to a function call either implicitly OR explicitly. The new keyword is a way to explicitly bind an empty object as a this context to a function call.

The binding precedence for the new keyword is high than other ways of binding. The binding precedence is:

  • The new keyword
  • Function invoked by call OR apply method. Note that the bind method internally uses the apply method.
  • Context object on which the function is invoked on. Eg: myObject.functionName
  • Default binding, where the this context is the global object, except in the strict mode

Overwriting the this context

The only way to overwrite the this context is to use the new keyword. This will create a brand new object in the this context.

var article = {
  title: "Thinking...",
  whatIsThis: function () {
    return this;
  },
};

// Here the `this` keyword refers to the `article` object
console.log(article.whatIsThis());
// Output - { title: 'Thinking...', whatIsThis: [Function: whatIsThis] }

// Using `bind` to explicitly bind `this` to the `context` object
var context = { title: "The new Keyword in JavaScript" };
var boundedFunction = article.whatIsThis.bind(context);

console.log(boundedFunction);
// Output - [Function: bound whatIsThis]

console.log(boundedFunction());
// Output - { title: 'The new Keyword in JavaScript' }

// Using `new` to override `this` with a new object
var newBoundedFunction = new boundedFunction();
console.log(newBoundedFunction); // <- new `this` context
// Output - whatIsThis {}

Conclusion

The new keyword has nothing to do with the “constructor call”. Its purpose is to redefine the this context and also establish a prototype link between the instance and the .prototype property of the constructor function.

If you liked this post then do 👍🏼 like and give your 🎙 feedback. I’ll be writing articles on the this keyword and Prototype so 🔥 follow to stay up to date with my new posts.

https://media.giphy.com/media/3ohs7KViF6rA4aan5u/giphy.gif