This content originally appeared on DEV Community and was authored by Vishwajeet Mishra
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
This content originally appeared on DEV Community and was authored by Vishwajeet Mishra
Vishwajeet Mishra | Sciencx (2025-01-31T10:35:10+00:00) Javascript functions with and without parentheses. Retrieved from https://www.scien.cx/2025/01/31/javascript-functions-with-and-without-parentheses/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.