Skip to content
Related Articles

Related Articles

Improve Article

What is the new keyword in JavaScript ?

  • Last Updated : 30 Sep, 2021

In this article, we will understand exactly what the new keyword is, and why we use the new keyword, and how we can use the new keyword.

The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

new constructor[([arguments])]

Why do we use the new keyword in JavaScript?



These are the following features to use the new keyword:

  • The new keyword creates a new empty object, with a type of object.
  • The new keyword sets the internal prototype property of the constructing function.
  • The new keyword binds this variable to the newly created object.
  • The new keyword returns the new object.

Example 1: In the below example, we will create a message function to print names with greetings and we will create an instance of message function. 

Javascript




<script>
    function message(name) {
        this.greeting = "Hey " + name;
    }
    name = "Vikash";
    var m = new message(name);
 
    console.log(m.greeting);
</script>

Output: Output on console 

Hey Vikash

Example 2: In the below example, we will create a student function and create an instance of the function using the new keyword as shown below.

Javascript




<script>
 
    // Function declaration
    function Student(name, age) {
        this.name = name;
        this.age = age;
    }
 
    // Create an instance of function
    var stud = new Student('Vikash', 22);
 
    console.log(stud.name);
    console.log(stud.age);
</script>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :