Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Array Iteration Methods Array Iteration Examples Using forEach()

Dom Ss
Dom Ss
4,338 Points

What would be the difference between (item.toUpperCase()) and (item.toUpperCase) without ()

For instance, in React course we sometimes called functions without () because we wanted these functions to be executed by callbacks.

(functionName) => { }

Is my understanding correct?

Why cannot this happen when we use:

const capitalizedFruits = []

fruits.forEach( item => {
 capitalizedFruits.push(item.toUpperCase)
});

and we need to use

const capitalizedFruits = []

fruits.forEach( item => {
 capitalizedFruits.push(item.toUpperCase())
});

My knowledge here lacks the distinction between methods and functions. Would appreciate if some1 could point me to a good explanation of that. Thank you !

1 Answer

Nicole Antonino
Nicole Antonino
12,809 Points

By typing (item.toUpperCase) it is only typing a reference to that function whereas (item.toUpperCase()) is actually calling the function in that exact moment.

Here's it explained more in detail on StackOverflow: https://stackoverflow.com/questions/42178136/when-to-call-function-vs-function-in-react-onclick

Dom Ss
Dom Ss
4,338 Points

Thank you Nicole. I checked the link and indeed what they confirmed is what I wrote above that when passing function as callback to event listeners in React you might want to omit () so that the function is called on the event, for instance when some1 clicks on the page.

This also would answer why it does not make sense to pass a reference to push() because we want the code to be executed immediately on run.