Skip to content
the poor coder

new operator in javascript

Poor Man
Published
Reading time
2 min read
On this page

New Operator in JavaScript#

The "new" operator in JavaScript is used to create a new instance of an object. It is used with constructor functions to create a new object of that function.

How to use the "new" operator:#

To use the "new" operator, you first need to create a constructor function. A constructor function is a function that initializes an object. You can create a constructor function like this:

Text

function Person(name, age) {
  this.name = name;
  this.age = age;
}

The above code creates a constructor function called "Person" that takes two parameters, "name" and "age". Inside the function, we use the "this" keyword to set the name and age properties of the newly created object.

To create a new instance of the Person object, we use the "new" operator like this:

Text

var person = new Person("John", 30);

The above code creates a new instance of the Person object with the name "John" and age "30". The "new" operator creates a new object and sets its prototype to the Person.prototype. It then calls the Person function with the newly created object as its "this" keyword.

Using "new" operator with built-in constructors:#

You can also use the "new" operator with built-in constructors such as String, Number, and Array. For example:

Text

var str = new String("Hello");
var num = new Number(10);
var arr = new Array(1, 2, 3);

The above code creates a new instance of a string, number, and array respectively using the "new" operator.

Using "new" operator with ES6 classes:#

In ES6, you can use the "class" keyword to define a class and create objects using the "new" operator. For example:

Text

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

var person = new Person("John", 30);

The above code creates a Person class with a constructor function that takes two parameters, "name" and "age". It then creates a new instance of the Person object using the "new" operator with the name "John" and age "30".

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC