What is the 'new' keyword in JavaScript to create an object and how to access values?

JavascriptWeb DevelopmentObject Oriented Programming

The new keyword creates an object in JavaScript. To access values, use the dot notation. Following is the code −

Example

function newObjectCreation() {
   this.firstName = "John";
}
var newObject = new newObjectCreation();
newObject.firstName="David";
console.log("The first name="+newObject.firstName);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo134.js

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo134.js
The first name=David
raja
Updated on 11-Sep-2020 06:29:12

Advertisements