Skip to content
Home » Program to Create and Introduce Persons in JavaScript

Program to Create and Introduce Persons in JavaScript

In this tutorial, we will learn how to create and introduce Persons in JavaScript using the provided code snippet. The code snippet demonstrates the usage of a constructor function to create objects with properties and methods. By following this tutorial, you will understand how to define and use constructor functions in JavaScript.

Code

function Person(name) {
  this.name = name;
  this.introduceSelf = function() {
    console.log(`Hi! I'm ${this.name}.`);
  }
}


const salva = new Person('Salva');
salva.name;
salva.introduceSelf();

const frankie = new Person('Frankie');
frankie.name;
frankie.introduceSelf();

Code Explanation

The given code snippet shows a constructor function called “Person” that takes a parameter named “name”. Inside the constructor function, the “name” parameter is assigned to the “name” property of the newly created object.

javascript
function Person(name) {
  this.name = name;
  this.introduceSelf = function() {
    console.log(`Hi! I'm ${this.name}.`);
  }
}

To create new instances of the “Person” object, we use the “new” keyword followed by the constructor function name. The created objects are stored in variables named “salva” and “frankie”.

javascript
const salva = new Person('Salva');
const frankie = new Person('Frankie');

To retrieve and display the value of the “name” property of each object, we can simply access the property using dot notation.

javascript
salva.name; // Output: 'Salva'
frankie.name; // Output: 'Frankie'

Similarly, to invoke the “introduceSelf” method of each object, we use the dot notation and call the method as a function.

javascript
salva.introduceSelf(); // Output: 'Hi! I'm Salva.'
frankie.introduceSelf(); // Output: 'Hi! I'm Frankie.'

The “introduceSelf” method prints a message to the console, introducing the Person with their respective names.

Conclusion

In this tutorial, we have learned how to create and introduce Persons in JavaScript using the provided code snippet. By using a constructor function, we can define properties and methods for objects, allowing us to create and customize multiple instances of the same object type. This concept is fundamental in JavaScript and is widely used in web development. With the knowledge gained from this tutorial, you can explore further and create more complex objects and applications in JavaScript.

Also checkout the following codes.


Program to Create a Hello World API using AWS Lambda and API Gateway
Program to Group Data Based on Property in JavaScript