This post will describe the use of init() in JavaScript.
What is the Use of init() in JavaScript?
“init” stands for “initiate”. Generally, it is utilized to create a “new Object()”. The init() function is not a built-in feature of JavaScript but it is a naming convention that is utilized for designing a function and is responsible for initializing or setting up a program or application. In jQuery, the “init()” function is used to return a new “jQuery object”.
The init() function can be used in a variety of ways such as creating and initializing objects or classes, setting up global variables and constants that are utilized in the program, and so on.
Example
In JavaScript, we can create an object using a constructor call as we will do in the given example. First, create a class “StudentDetails”, and create a constructor in it with three parameters “name”, “age” and “grade”. Set the values of these parameters using the “this” keyword:
constructor(name, age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
}
Create an object of the class using the “new” keyword that will call the constructor:
Now, print the values of the object’s properties on the console:
console.log(student.age);
console.log(student.grade);
Output
In JavaScript, the init() function can also be used as a constructor for creating an object. For this, define a function with the name init() and utilize the “Object.create()” method for creating a new instance of the object.
Here, we create a constructor using the “init” and for printing the values of the object’s parameters/properties, we will create a function “print”:
init: function(name, age, grade){
this.name = name;
this.age = age;
this.grade = grade;
},
print: function(){
console.log(this.name);
console.log(this.age);
console.log(this.grade);
}
};
Call the “Object.create()” method by passing the class “StudentDetails” as an argument to create a new object:
Now, invoke the “init” and “print” functions with the object. Here, “init” will help in the instantiation of object properties. In fact, init is a constructor call on the class “StudentDetails”:
student.print();
The output shows that the object has been successfully created and instantiated with its properties:
That’s all about the use of init() in JavaScript.
Conclusion
The init() function is not a built-in feature of JavaScript but it is a naming convention that is used for the designing of a function that is responsible for initializing or creating an object or a script. The init() function can be used in a variety of ways such as creating and initializing objects or classes, and setting up global variables and constants, and so on. This post described the usage of init() in JavaScript.