The new
keyword in JavaScript is used to create an instance of an object by calling the constructor method.
This means that every time you create a new instance, JavaScript calls the constructor method. This goes a long way in reducing repeat code, which makes debugging harder.
new
keyword?You might be wondering where the new keyword is needed and where you get to use it.
Let’s assume that you're building a children’s kindergarten program. This program takes in parameters such as age, location, and much more. New children are bound to be admitted to kindergarten at any time. You want to write a class that takes in the children's parameters without going through the tedious process of creating another class now and then. So, how do you do it?
You will create a single class that generalizes the children, then use the constructor method to store that age and location parameter.
// create the class as shown belowclass Child {constructor(age, location) {this.age = age;this.location = location}}
You will then use the new
keyword to call the Child
class every time an instance is generated.
class Child {constructor(age, location) {this.age = age;this.location = location}}// the new keyword at workconst Mark = new Child('Five years,', 'St. Peters Area,');const Brian = new Child('Seven years,', 'Karibu Estate,');console.log(Mark.location);console.log(Brian.age, Brian.location);
Note: The version of JavaScript is
v10.17.0
The Child
class allows you to create new Child
objects for every child in the kindergarten.
Let's look at what happens under the JavaScript hood when you use the new
keyword:
New objects get created from the already-defined properties in the class.
The first course of action is that a new empty object gets created instantly.
The prototype’s properties are set according to the constructor you used.
The properties are then bound by this keyword inside the constructor.
The newly created object gets returned.
The new
keyword makes it easier to avoid repetitive code and makes it easier to debug our code as well. It is also foundational in learning object-oriented programming in JavaScript.