Don’t understand anonymous functions. Help? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Don’t understand anonymous functions. Help?

So I get adding the event listener, then passing it click. I know that add event needs to be passed 2 things. The second being a function. But I see things as if there are wires. I don’t know where the empty function parentheses wire goes. HTML <h1 class=“seanTitle”><\h1> JS //Assign selector to variable. let seanTitle = document.querySelector("h1.seanClass"); //Create function to take effect. seanTitle.addEventListener('click', () => { //Add styling you want. seanTitle.style.color = "blue"; });

20th Jun 2021, 6:24 PM
Liquid T
Liquid T - avatar
3 Answers
+ 4
So basically anonymous functions are as it suggests “Function without any name”. Now where we use it? Well its used at a place where you have a function that you only need to use once . so its really a good idea to use anonymous functions as callback function as its only gonna be used once. the ()=>{} is just a short hand of function(){} so you can very well use : seanTitle.addEventListener('click',function(){ seanTitle.style.color='blue'; }); instead of : seanTitle.addEventListener('click',()=>{ seanTitle.style.color='blue'; });
20th Jun 2021, 6:39 PM
Prashanth Kumar
Prashanth Kumar - avatar
+ 3
understanding comes with doing. Take it as it is, use it often... u will understand
20th Jun 2021, 7:16 PM
Oma Falk
Oma Falk - avatar
+ 2
about 3 function declaration ways (+ variants): // named declaration function namedFunc() { } // can be assigned to variable: var anyName = namedFunc; // hoisted: can use them sooner than declaration // keyword expression (named or not) var kwFunc1 = function funcName() { }; var kwFunc2 = function() { }; // arrow expression (anonymous) var arrowFunc = () => { }; // NOT hoisted: can only use them after (in program flow) declaration arrow functions can never bind 'this' object... so slightly difference in using as event listener callback: cannot access target object with 'this' however, allow access of original 'this' target object if declared at scope with 'this' object (constructors, methods) // object literal function declaration other way var o = { methodName: function() { }, }; or var o = { methodName() { }, }; act as keyword declaration: 'this' inside function is the object on wich is attached the method as variable can store function, argument also: callback used as event listener
20th Jun 2021, 8:41 PM
visph
visph - avatar