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 trialArman Taher
2,019 PointsWhy use on('click',function (event){console.log(event)} instead of on('click',function (){console.log(event)}
Why use on('click',function (event){console.log(event)} instead of on('click',function (){console.log(event)}
3 Answers
Alex Warner
Courses Plus Student 4,987 PointsLet’s break this down to make it a little clearer:
You’re calling the .on method and passing it two arguments. The first argument is the type of event to listen for and the second is the function to execute when the actual event fires (in this case a click). This function is commonly referred to as a callback function.
When the event fires JavaScript creates an Event object that contains properties about the event that just fired.
Then the callback function is executed. You don’t have to provide an argument to the callback function but if you want to access any of the information about the event you have to pass the newly created Event object as an argument in your function. You can call it ‘event’, ‘e’, ‘meatball’, whatever you want. The callback function knows that if you provide an argument it represents the Event object.
So: .on( ‘click’, function(e) { console.log(e.type); // ‘click’ }
.on( ‘click’, function() { console.log(e.type); // undefined }
In the second example the Event object wasn’t passed to the callback function so if you reference it within the function definition (ie, e.type) it won’t know what you’re referring to.
Raja Kannan
6,590 PointsHi, function(event) in this event is a parameter. If we use parameter in the function, we have to use it while callling the function also. So, we use on('click',function (event){console.log(event)} instead of on('click',function (){console.log(event)}
Ari Misha
19,323 PointsHiya there! Event is an object literal containing all kinds of information. But to access that information in our callback function, we're gonna have to pass it as an argument so that it'll be available in our code block when we need it. Now, the code your provided in your function is basically a simple way of debugging. In the same piece of code, you're just logging out the event object literal in the console.