Javatpoint Logo
Javatpoint Logo

JavaScript Factory Function

The Factory Function is related to the constructor function or class functions. However, it produces and returns an object without requiring a new one.

Factory Functions in JavaScript are identical to constructorfunctions. However, they don't require the 'this' keyword for inner values or the 'new' keyword when initialising new objects. Factory Functions can have inner values, arguments, etc., like regular functions. Unlike normal functions, factory functions return an object with any value, method, etc...

If we need to produce several objects that contain the same logic, we may write the logic in a function and utilise it as a factory. It's like an actual factory making items.

Syntax

The following factory syntax is used to return multiple data using a function.

  • Here, the data is variable to get input value using factory function and return factory variable data.

Examples

The following examples help to know about factory function and how to operate it using javascript.

Example1

The following factory function example is used to display multiple data using the function. The data is shown in the console using the console.log function.

Output:

The image shows multiple data using a single function.

JavaScript Factory Function

Example2

The following factory function example is used to display mathematical operation and its output.

Output:

The image shows multiple data using a single function.

JavaScript Factory Function

Example3

The following factory function example is used to display multiple data using the function. The data is shown in the console using the console.log function. Here, we use "var" to create variable.

Output

The image shows multiple data using a single function.

JavaScript Factory Function

Example4

The following factory function example is used to display multiple data using the function. The data is shown in the console using the console.log function. Here we can use the fullname with a different object in the factory function.

Output

The image shows multiple data using a single function.

JavaScript Factory Function

Example5

The following factory function example is used to display multiple nested function operations using the function. Here we can create two methods, division and multiplication, inside of the factory function. We can place a single value for all functions then javascript operates both multiplication and division for the single factory functions value.

Output

The image shows multiple data using a single function.

JavaScript Factory Function

Conclusion

The factory function in JavaScript is used to display multiple values using a single function. It is used to display data as per requirement.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA