Skip to content

New keyword in JavaScript | Basics

  • by

The new keyword is used in JavaScript to create an object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things:

new constructor[([arguments])]
  1. Creates a new object
  2. Sets the prototype of this object to the constructor function’s prototype property
  3. Binds the this keyword to the newly created object and executes the constructor function
  4. Returns the newly created object

New keyword in JavaScript

Simple example code can create an instance of a user-defined object type or of one of the built-in object types that have a constructor function.

<!DOCTYPE html>
<html>
<body>

  <script>
    function Car(make, model, year) {
      this.make = make;
      this.model = model;
      this.year = year;
    }

    const car1 = new Car('Eagle', 'Talon TSi', 1993);

    console.log(car1);
  </script>

</body>
</html> 

Output:

New keyword in JavaScript

Javascript creates prototype objects

function MyFunc() {
  this.name = "Hello";
}
MyFunc.prototype.book = "Javascript";
let obj1 = new MyFunc();
console.log(obj1.name);
console.log(obj1.book);

Output: Hello

Javascript

Comment if you have any doubts or suggestions on this JS keyword topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *