DEV Community

Albert Baliński
Albert Baliński

Posted on

The new keyword in Javascript

In this article, I will explain the basic concept, which is the new keyword.
In Java language, we have a class, which is a blueprint from which you can create an instance. An object is an instance of a class. But in Javascript, technically speaking, there is no such thing as a class. Even though we have the class keyword in the newer versions of Javascript, it is just a special syntactic sugar added in ES6 to make it easier to declare and inherit complex objects. Classes in JavaScript are a special syntax for its prototypical inheritance model that is a comparable inheritance in class-based object-oriented languages.

function f() {
  return 5
}
typeof f() // number
typeof new f() // object

As you can see, adding the new keyword creates a new object. Why do we need it? Let’s run the code below (in a browser).

function Person(name) { 
  this.name = name
}
const person1 = Person('James')
console.log(person1.name) // undefined 
console.log(window.name) // James 

Why?

Remember that Javascript (just like Python) is a scripting language – the interpreter reads the code and executes it line by line. In the code above, this refers to changes every time the execution context is changed – in the Person function it points to the global object. What we need here is a new object, which we can create using {}

var person1 = {}
Person.call(person1, 'james')
console.log(person1.name) // james

Above we used the call method, which calls a function with a given this value and arguments provided individually. Or, much simpler, we could do it in one line:

const person2 = new Person('Mary')
console.log(person2.name) // Mary

By adding the new keyword, we return a new object to which this is pointing to, making the code working as expected.!

Top comments (0)