JavaScript new Operator

JavaScript new operator is used to create a new object of user-defined type.

Example

In the following example, we define a class Student. We shall use new keyword to create an object of type Student.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        class Student {
            constructor(name, roll_no) {
                this.name = name;
                this.roll_no = roll_no;
            }
            getDetails() {
                return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
            }
        }
        var s1 = new Student('Arjun', 14);
        var result = s1.getDetails();
        document.getElementById("output").innerHTML = result;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to use new operator to create a new object of user-defined class type.