noha Deeb
noha Deeb

Reputation: 1

Immediately invoked arrow function expression

Here's a function where it suppose to work when I click a "button but surprisingly it immediately invoked without calling!

	const show_card = (shopping_card_checkout) =>  {
		console.log("ali el-deeb");
	};
  document.querySelector('.fa-shopping-cart').addEventListener('click', show_card()) ;

If I tried to redo the code after the event listener it says reference error as I called the function before declaration.

Help a beginner.

Upvotes: 0

Views: 408

Answers (1)

Bojoer
Bojoer

Reputation: 948

Saw your post request in JS FB group and thought I'd answer here.

First you need to use document.ready or make sure that all js is loaded as last cause else the element might not yet exist. This is not th cause of your problem btw. The problem I explain as last but some advice. You use a class and querySelector, querySelector will fetch the first element in the document and if you want all elements returned you need querySelectorAll and this is not unique or would you like to bind the same action and functionality to many elements? So better would be to use the unique id of an element and use something like:

const myElement = document.getElementById("idName");
myElement.addEventListener("click", myFynction);

const myFunction = () => console.log("Clicked");

The real cause of your issue You bind the function to the click event and bind it with () behind it and that triggers the execution cause now you don't bind the function but the result of the bound function, you can't pass parameters like that to a bound event. You will need to fetch them inside the function cause only event and a callback can be triggered.

So your working code is:

const show_card = (shopping_card_checkout) => console.log("ali el-deeb");
document.querySelector('.fa-shopping-cart').addEventListener('click', show_card);

And if only one return or one statement inside an arrow function there is no need for the curly brackets and no need to use return since it will automatically return the result of the oneliner.

Upvotes: 1

Related Questions