What is the reason behind functions not requiring (args) when called with parameters?

Have you ever noticed the difference in behavior between these two code snippets?

var foo = document.getElementById("foo");
foo.addEventListener("keydown", foo);
function foo(e){
 console.log(e.keyCode);
}

And this one:

var foo = document.getElementById("foo");
foo.addEventListener("keydown", foo(e));
function foo(e){
 console.log(e.keyCode);
}

It may seem confusing, but sometimes passing parameters can change how things work:

var foo = document.getElementById("foo");
foo.addEventListener("keydown", foo("Hello, world!"));
function foo(e){
 console.log(e);
}

So why does this happen? It's a bit of a mystery!

Answer №1

However, in certain scenarios when passing something through a parameter, the approach would be:

var foo = document.getElementById("foo");
foo.addEventListener("keydown", foo("Hello, world!"));

function foo(e){
 console.log(e);
}

Actually, that is incorrect. By doing this, you would immediately invoke `foo` with its argument, resulting in the return value (which, in your case, is `undefined`) becoming the callback reference for the `keydown` event, and `undefined` cannot be a callback reference.

Let's see this in action. Below, 'Hello, world!' gets printed to the console right away, and nothing happens when a key is pressed down in the input field:

var input = document.getElementById("input");
input.addEventListener("keydown", foo("Hello, world!"));
function foo(e){
 console.log(e);  // Printed to console immediately!
}
<input id="input">

The second parameter for .addEventListener() requires a function reference, which can be provided in various ways:

Pass the name of the function (without parenthesis):

 .addEventListener("click", foo);

Provide an anonymous function (just pass the function without invoking it):

 .addEventListener("click", function(){ /* function body */ });

Include code that returns a function as the callback reference (note the parenthesis here) where `foo` is invoked first and the returned value, which should be a function, acts as the callback reference:

 function foo(){
   return function(){ console.log("Hello, world!"); };
 }

 .addEventListener("click", foo());  // foo is called first

However, if `foo` needs to be the function reference AND it requires arguments, including parentheses will invoke the function immediately. Therefore, you must wrap the function call in an anonymous function, as shown previously:

function foo(e){
 console.log(e);  
}
var input = document.getElementById("input");

// The anonymous function serves as the reference to execute when 
// the event occurs. It will then call foo with the necessary arguments.
input.addEventListener("keydown", function(){ foo("Hello, world!"); });
<input id="input">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for creating a server-side API call?

I've designed a front-end application that uses an API to retrieve data. The problem I'm facing is that in order to access the API, I need to use an API Key. If I include the API key in the client-side code, it will be visible to users. How can I ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

A guide on parsing a nested JSON file with ExtJS 4

Here is the content of my JSON file named "jobInfo.json": { "job": { "id": 1, "name": "Job 1", "description": "bla bla bla", "locations": { "type": "FeatureCollection", "features": [{ "id": 1, "t ...

The form post request cannot recognize the undefined variable

When attempting to send values through an HTML form and retrieve it in console.log, I encounter an error that says "TypeError: Cannot read property 'fName' of undefined," despite declaring it in the form name. signin.html : <!doctype html> ...

Searching for the most recent entry from a related group within an HTML table using jQuery

I have a list of students in different classes that looks like this Class StudentName RollNo. Class X Sarah 1 Class Y David 2 Class Z Emily 3 Class W Adam 1 C ...

I am unable to view the map on my webpage. This issue only arises when I apply a CSS style to it

Hey there! I'm having trouble displaying a map on my website. For some reason, the map is not showing up even after updating the Google secret key in my code: <?php session_start(); include '../../WSweb/serv.php'; if(isset($_SESSION[&a ...

Eliminating the glow effect, border, and both vertical and horizontal scrollbars from a textarea

Dealing with the textarea element has been a struggle for me. Despite adding decorations, I am still facing issues with it. The glow and border just won't disappear, which is quite frustrating. Could it be because of the form-control class? When I rem ...

Caught off guard by this promise: TypeError - Attempting to access a property that does not exist in my Ionic 2 application

I'm encountering an issue with native Facebook login that displays the following error message: Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined https://i.sstatic.net/PDWze.jpg I have shared my entire project ...

Ensure that the central section of the slider remains illuminated

Looking for help with customizing my "product" slider, lightSlider. I want the middle div to always be highlighted when navigating through the slider. Here's what it looks like currently: Link to screenshot - current. My goal is to achieve this look: ...

The GitHub Pages website is not displaying exactly like it does when running locally with a live server

Currently in the process of creating a compact website where users can input an anagram and receive all potential words that can be formed from it. Additionally, upon receiving these words, there is an option to click on one for its definitions. The site ...

Updating multiple fields in a SqlDataSource using a single UpdateCommand

Seeking a solution with SqlDataSource, I am facing the challenge of using two similar update commands. Is there a way to combine these commands into one within the SqlDataSource? While I understand how to work with normal parameters, I am unsure about chan ...

Is there a way to manually trigger a re-render of all React components on a page generated using array.map?

Within my parent component (Game), I am rendering child components (Card) from an array. Additionally, there is a Menu component that triggers a callback to Game in order to change its state. When switching levels (via a button click on the Menu), I want a ...

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

Ways to verify if an element includes a specific class in JavaScript

When the mouse hovers over each paragraph within the DIVs with the "change" class, the font color should turn red, and revert back to black when the mouse is not on them. Here's my current code: var paragraphs = document.getElementsByTagName('p& ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

"An issue has arisen in MongoDB when attempting to save data, resulting in an error message

Having trouble inserting data into MongoDB with Node.js. Encountering an error in the final line of code. Here are the execution logs: { _id: 56e90c1292e69900190954f5, nfs: [ 'ebdp1', 'ebdp2', 'ebdp3', 'ebdp4' ], s ...

Guide to profiling resources in Node.js applications

When developing Node.js applications, it's important to keep track of how your code is performing in terms of memory and IO. By monitoring these metrics, you can identify which parts of your code are causing delays or consuming excessive resources. Th ...

Content moves as you scroll, not within a lightbox

I have implemented lightbox style overlays for my 'Read More' content on my website. However, I am facing an issue where the content within the lightbox does not scroll; instead, the background page scrolls. Any assistance with resolving this p ...

Having difficulty adding a Dropdown Menu in a Pop-up Box

I am trying to incorporate a select menu inside of a popover, but every time I attempt to do so, the popover content block remains blank. The popover is associated with a side menu item called "Date History". Below is the code snippet I am using to constr ...

What is the best way to expand the subcategories within a list?

I have successfully implemented a script to open my hamburger menu. However, I am facing an issue with subitems as some list items contain them. How can I modify the script to ensure that the subitems expand when clicked instead of just hovering? functi ...