Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the function is used without parenthesis in addEventListener?

I am not able to understand how this addItem() and removeItem() is called without parenthesis in addEventListener('click', addItem).

var addButton = document.getElementById('add');
addButton.addEventListener('click', addItem);

var removeButton = document.getElementById('remove');
removeButton.addEventListener('click', removeItem);

function addItem(){
    console.log('Add Button clicked');
}

function removeItem(){
    console.log('Remove Button clicked');
}
like image 220
Mercury1337 Avatar asked Jun 03 '19 08:06

Mercury1337


People also ask

Can you call a function without parentheses?

When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.

What is the difference between calling function with parentheses and without in JavaScript?

With parenthesis the method is invoked because of the parenthesis, the result of that invocation will be stored in before_add. Without the parenthesis you store a reference (or "pointer" if you will) to the function in the variable.

Why do some methods not have parentheses?

Without parentheses you're not actually calling the function. A function name without the parentheses is a reference to the function. We don't use the parentheses in that code because we don't want the function to be called at the point where that code is encountered.

Which method does not require the use of parentheses in JavaScript?

Method 1: Using the new operator: The new operator is used to create an instance of an object which has a constructor function. This constructor function can be used to write our own function and then be invoked by the new operator.


1 Answers

Because in this context, addItem is used as a function reference rather than the return value of the function.

If you did this:

addButton.addEventListener('click', addItem());

Then addItem would be executed straight away, and whenever addButton was clicked, the return value of addItem (which is undefined) would be called. This would result in an error, because undefined is not a function.

Here, you're saying when I click addButton, lookup the function reference I passed, and execute it.

You can also write this two different ways:

addButton.addEventListener('click', "addItem()");
addButton.addEventListener('click', function() {
    addItem();
});

Both of the above will still result in the same output as your original code.

like image 95
Jack Bashford Avatar answered Sep 26 '22 15:09

Jack Bashford