Trivia Questions2 min readPremium

Explain the difference between function Person(){}, var person = Person(), and var person = new Person().

Understanding Function Declaration, Function Invocation, and Object Instantiation in JavaScript

In JavaScript, functions and objects play a pivotal role in the development of robust applications. The distinction between function Person(){}, var person = Person(), and var person = new Person() might seem subtle, yet it fundamentally affects how your code behaves. MDN’s new operator reference explains what changes when you add new.

Function Declaration: function Person(){}

Using function Person(){} declares a function named Person. This declaration creates a template for an action or object, but does not execute the function nor does it create an instance of an object. It’s akin to defining a recipe without cooking anything.

Function Invocation: var person = Person()

When you invoke a function with var person = Person(), you’re calling the Person function and assigning its return value to the variable person. If the Person function does not explicitly return a value, person will be undefined. Any assignments to this inside Person would also leak onto the global object in non-strict mode, or throw a TypeError in strict mode. This operation executes the function’s code, but it does not create an instance of an object defined by the function.

Object Instantiation: var person = new Person()

The expression var person = new Person() goes a step further by using the new keyword to instantiate a new object from the Person function. This process creates an instance of the Person “class” (JavaScript does not have classes in the traditional sense, but functions can be used to simulate them). The new object receives any properties the constructor assigns to this, and it inherits methods defined on Person.prototype through the prototype chain.

Conclusion: function Person() vs new Person()

Understanding these distinctions is crucial for JavaScript developers, particularly when dealing with object-oriented programming concepts. A function declaration outlines behavior, invoking a function executes behavior, and object instantiation creates a tangible entity based on the function’s blueprint. Each serves a different purpose in the lifecycle of a JavaScript application, from defining capabilities, executing logic, to creating entities that interact within the application.