Sitemap
Saurav sharma

Saurav sharma

Full stack developer

Constructor function in JavaScript

2 min readDec 4, 2023
Press enter or click to view image in full size
https://pixabay.com/photos/kids-play-games-childhood-4926029/

What is a constructor function in JavaScript:

A constructor function is just a regular function with the following specialties:

👉 (1) It should be executed with the “new” keyword.

👉 (2) The naming convention should be with Capital letters.

👉(3) Returns from constructor function: Usually constructor functions are not supposed to return anything because they mostly deal with this which is returned, but if an explicit return is there, then if the return is called with an object, an object is returned otherwise ‘this’ value.

  • If a constructor explicitly returns an object, that object is returned instead of the default this.
  • If it returns a primitive (string, number, boolean, null, undefined), it’s ignored, and this is returned instead.

👉(4) Arrow function can not become constructor function: Arrow function does not have its own ‘this’ so they can not behave like a constructor function.

Get Saurav sharma’s stories in your inbox

Join Medium for free to get updates from this writer.

let’s understand the example

function Car(name, modelYear) {
this.name = name;
this.modelYear = modelYear;
}
let test = new Car("fortuner", 2023);
let test2 = new Car("shift", 2020);

console.log(test.modelYear); //output 2023
console.log(test2.name); //output shift

Step (1) Declares a constructor function having two parameters.
Step (2) Next we set name and modelYear to the new object instance created using the ‘new’ keyword.
Step (3) Create a test instance of Car with name and modelYear values.

That is how we can create as many objects as we want easily.

‘This’ keyword in the Constructor function:
When the ‘this’ keyword is used in the constructor function, this refers to the object when the object is created, in other words, this refer to the newly created object.

Note: In the above example name or modelYear refers to the object created using a new keyword.

Object literal vs Constructor function:

(1) Object literal is usually helpful for creating a single object but the Constructor function is used to create more similar objects.

(2) The Constructor function creates a unique object and if you add more properties to it then it will only associated with it but in the case of an object literal if you make any changes in the clone object it will reflect in the original object also.
Built-in Constructor:
There are the following Constructor functions available in javascript


let obj= new Object(); //a new Object object
let str = new String(); // a new String object
let num =new Number(); // a new Number object
let bool= new Boolean();// a new Boolean object

This is all about the Constructor function. I hope you like this article, please share your feedback in the comment section.

Thanks and Regards
SAURAV KUMAR SHARMA

--

--