DEV Community

Cover image for Javascript functions with and without parentheses
Vishwajeet Mishra
Vishwajeet Mishra

Posted on

Javascript functions with and without parentheses

Often times we have seen that the javascript functions are written without parentheses which confuses most of the beginners as well as experienced folks. Today I am going to give a simplest explanation of why functions with and without parentheses are used.

let bmwCar = {
make:'BMW',
model:'X1',
colour:'Red',
getCarDetails: function(){
return this.make+' '+this.model+' '+this.colour;
}
}

let mercedesCar = {
make:'BMW',
model:'X1',
colour:'Red'
}

in the above code, mercedesCar object does not have getCarDetails function. but in javascript we can borrow methods from other object like below.

let carDetails = bmwCar.getCarDetails //this is where we don't use parentheses as we are not invoking a function. we just want to give reference and assign it to a variable.

if we want to print mercedesCar details we need to bind getCarDetails method from bmwCar to it as below.

let carDetails = bmwCar.getCarDetails.bind(mercedesCar)
console.log(carDetails()) // now using here parenthesis will invoke the method and results will be displayed

Conclusion : Parenthesis in javascript are only used when we need to invoke a function. we don't use parenthesis if we only need to give reference to it

Top comments (0)