Invest with Cake DeFi and get guaranteed returns from your crypto assets. Register Now
All Articles

Difference between: function Person(){}, var person = Person(), and var person = new Person()?

Technically speaking, function Person(){} is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.

function Person(name) { = name

var person = Person() invokes the Person as a function, and not as a constructor. Invoking as such is a common mistake if the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return undefined and that gets assigned to the variable intended as the instance.

var person = Person('John')
console.log(person) // undefined
console.log( // Uncaught TypeError: Cannot read property 'name' of undefined

var person = new Person() creates an instance of the Person object using the new operator, which inherits from Person.prototype. An alternative would be to use Object.create, such as: Object.create(Person.prototype).

var person = new Person('John')
console.log(person) // Person { name: "John" }
console.log( // "john"


Published 29 May 2021

Recent Posts

Warning: Can’t perform a React state update on an unmounted component

If you are a react developer, there is a good chance that you faced this warning at least once.

Angular Singapore

Follow @angularsg for the upcoming events :)

Follow @tuantrungvo on Twitter for more!