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');
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With