This page looks best with JavaScript enabled

Javascript New Keyword

 ·   ·  ☕ 2 min read

New operator is used to initialize objects and create a new instance of the object.

You would have seen new used in the object context in an earlier post. The usage is something like the below -

1
2
let worldExists = new Boolean(false);
console.log(worldExists); // [Boolean: false]

worldExists is an object that has a value of type ‘boolean’. Refer the post linked above to know the difference.

Since everything (almost) is an object, new works very similarly in its use cases.

1
2
let todayDate = new Date();
console.log(todayDate); // 2018-12-25T15:31:32.359Z

This creates an instance of Date, which by default initializes with today’s date.

The logic extends to functions as well.

1
2
3
4
5
6
7
8
function sum(x, y) {
  this.x = x;
  this.y = y;
  this.sum = this.x + this.y;
}

let f1 = new sum(3, 2);
console.log(f1.sum); //5

Here, new creates the new instance, passes the variables to function, initiates variables using this context and assigns the newly created object to f1.

Javascript does not have ‘true’ classes - the function definition is treated as a prototype. The variables passed while creating the object is passed to constructor, bound to this within the function, and either the return variable or this itself is returned.

If you are left wondering on shared variables similar to a class -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function sumMultiply(x, y) {
  this.x = x;
  this.y = y;

  this.sum = this.x + this.y;
  this.multiplier = this.sum * this.factor;
}

sumMultiply.prototype.factor = 2;

let addMul = new sumMultiply(3, 2, sumMultiply.prototype.factor);
console.log(addMul.multiplier); //5

let addMulDeux = new sumMultiply();
console.log("addMulDeux.factor: ", addMulDeux.factor); // 2

If you are now left wondering just why you should create an object rather than using the function directly, you would have to hold your breath till another day.

No.. no.. Don’t hold your breath - I was kidding. Just Google it.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things