-3

Sorry for the ambiguous title, I just didn't know what else to put. Im learning JS and in the video the person does this. JS code

When he calls the addListAfterKeyPress method at the bottom, why does the function call work? I thought he would have to put in a argument for the addListAfterKeyPress to take in since it has an event parameter. But in the end the code works perfectly. And also, when can i call a function that takes a parameter without explicitly passing one like how he did it in the picture?

Cris
  • 121
  • 1
  • 10

1 Answers1

1

This is a so called callback.

addListAfterKeypress at line 30 is not a call to this function, it is just saying, whenever the event keypress is raised on this input element, call this function.
Who is calling the function is the DOM library, indeed. You just have to pass a pointer to the function to be called.
Even more, the addListAfterKeypress function expects an event parameter, which will be provided to the function by the DOM library.

I think it is a bit more understanding by looking at an annonymous function there.

input.addEventListener('keypress', event => {
   // This will be run whenever the input raises an event of type 'keypress'
   // Here, the DOM library provides me an event parameter
}); 

Edit on demand:
Be aware, I am using ES6 just for comfort.
Suppose having this function

const callback = () => {
    console.log(`My callback function is being executed`);
};

I will be using setTimeout to mock the HTML events. setTimeout is a function that expects a callback to execute after n milliseconds.
The first parameter is the callback itself, the second is the amount of milliseconds, n.
See https://www.w3schools.com/jsref/met_win_settimeout.asp

setTimeout(callback, 500); // After 500ms, function callback will be fired

Here, I am just passing a pointer to the setTimeout function. This pointer must point to a function that will be called by setTimeout.

Let's write our own function that takes a callback as a parameter.

const callback2 = (number) => {
    console.log('I received this parameter', number);
};

const callbackWrap = (callback, n) => {
    // Here, callback parameter is a function that I can invoke, actually
    console.log('The wrapper will execute the function passed as parameter');
    callback(n);
};

Now, we can call the wrapper pointing to the new callback (callback2).

callbackWrap(callback2, 3);
callbackWrap(callback2, 4);

Or, we can define our function directly on the parameter list.
That is, we are passing an annonymous function

// p is the parameter of the callback function
callbackWrap(p => {
    // Since callbackWrap will call the function parameter
    // by passing a single parameter,
    // the function I am declaring, expects that parameter
    console.log(`Received ${p} inside the annonymous function`);
}, 'Parameter');

So, to summerize a bit, just the same way you can declare a variable (let's say, of type number) and then pass it to a function as a parameter, you can declare a function to pass it the same way.

const normalParameter = 30;
const functionParameter = p => console.log('Another callback', p);
callbackWrap(functionParameter, normalParameter);

// Or maybe passing more complex parameters
const anotherParameter = [1, '2', {3: 4}];
callbackWrap(functionParameter, anotherParameter );

Hope it clarifies a bit.

VRoxa
  • 973
  • 6
  • 25
  • I dont really understand how or why callbacks work. I read the stackoverflow answer on it but I didn't understand too much from it. Do you think you can give me a simple rundown on it? – Cris Apr 06 '20 at 01:33
  • From my understanding, callbacks are used for asynchronous programming. And so you use the callbacks to start a process so that it's ready to be executed immediately after some event. So in the example you posted, ```event``` instructions are being processed in the background and therefore are ready when the ```addEventListener``` function calls it in its own function. Is that accurate or am I missing or misunderstanding something? – Cris Apr 06 '20 at 01:41
  • 1
    I am typing some chunks of code to explain it. Wait for me – VRoxa Apr 06 '20 at 01:47
  • @Cris Callbacks are not just for async, but often are used for them. – Keith Apr 06 '20 at 01:51
  • Good answer but be carefull, JS does not have pointers, that's a bit missleading. – kevinSpaceyIsKeyserSöze Apr 06 '20 at 06:41
  • Well, it does. When you declare `let a = {};`, `a` is a pointer to the heap where an object is stored. If you initialize another variable with `a`, you are just pointing to the same address in memory. Check this tiny test: [Demonstration](https://jsfiddle.net/9gdqf2jb/1/). Since functions are stored in variables as well, whenever you pass a function as a parameter, you are pointing to the address where the function is stored. So yes, JS has pointers, no matter if we are not able to operate them (like C++, for instance). – VRoxa Apr 06 '20 at 12:30
  • @VRoxa I definitly know what you mean but you can't call this pointers because they arent. Read [this](https://stackoverflow.com/questions/17382427/are-there-pointers-in-javascript) – kevinSpaceyIsKeyserSöze Apr 07 '20 at 19:47