0

if I use arrow function instead of normal function flip and do add addeventlistiner to it before initializing the arrow function then I am not able to call the function.

**

  • Not Working

     console.log(cards);
    
     cards.forEach((card) => 
      card.addEventListener("click",flip));
    
    
     var flip = ()=>{
         console.log("card flipped");
     } 
    
    
    

output : on clicking of the card it should give me the output as "card flipped", but it does not do anything.

  • Working
    var flip = ()=>{
    console.log("card flipped"); }

    const cards = document.querySelectorAll(".card");

    console.log(cards);    

    cards.forEach((card) => 
    card.addEventListener("click",flip)); 

output : on clicking of the card it is giving me the output as "card flipped",

How do I call the arrow function before initializing it ?

  • 1
    You cannot do that. – Pointy Sep 03 '22 at 16:23
  • 1
    "*How do I call the arrow function before initializing it ?*" **why?** What you're asking for is ***impossible***. Either you define the function *before*, or you use a regular function, or you create a new function entirely. There is no reason to *need* to do it as you've described. – VLAZ Sep 03 '22 at 16:31

1 Answers1

0

You can't call an expression function before the definition.

However, if you wanted to use a declared function instead of an arrow function with the 'function' tag, you could arrange your code in the way you described.

Example:

function flip() {
console.log('card flipped)
}

Similar question:

why-can-i-use-a-function-before-its-defined-in-javascript