Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Dom Ss
Dom Ss
4,339 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,834 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,339 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.