#Callback Functions - JS

1 messages · Page 1 of 1 (latest)

covert bone
#

Hey guys , it seems that i didn't understand this concept 100% , could someone help me to understand it and explain it to me like a 5 years old kid
thanks ❤️

pseudo sierra
#

search for JavaScript closure

minor wedge
#

Can you try to explain how you understand callbacks in your own words?

pseudo sierra
#

closures and scope are like inner class in Java

#

because functions are first class citizen and an actual class in JavaScript

#

callback are executed by the run-time, check the first video, it's very visual

#

call back in general is just a pointer to some function / code and you tell that function that you call, please call me back when you need me

#

a bit like a push notification.

#
window.setTimeout(
   function(e)  // = The callback, 
                // (e) the timeout event object
   {
       console.log("The event was : " + e);
   },
   100  // = 100ms
);
#

so this means that the run-time loop will execute "all your code"
and once it is done, it will call you back at least 100ms later

#

If your main code is SUPER SLOW, it might call you back minutes later, which is >>> 100ms

#

In normal web code, this never happens, so you normally get normal behavior of being call back within 100ms

#

Now you can write this code like this:

   function myCallBack(e)  // = The callback, 
                // (e) the timeout event object
   {
       console.log("The event was : " + e);
   }

window.setTimeout(
   myCallBack, // Pointer or Reference to the function above.
   100  // = 100ms
);
#

or like this and name the anonymous function

#
window.setTimeout(
   function myCallBack(e)  // = The callback, 
                // (e) the timeout event object
   {
       console.log("The event was : " + e);
   },
   100  // = 100ms
);
covert bone
#

wait wait wait @pseudo sierra

pseudo sierra
#

In Java 7 and earlier this would be a fully fledge class instance
In Java 8+ that could be a "lambda", which is also a closure

covert bone
#

we're just learned the basics and yesterday we learned about promise

pseudo sierra
#

OK 😄

covert bone
#

@minor wedge now , callback functions uses basically for async tasks , and its the abiility to call a function from another function with parameters

pseudo sierra
#

Did you learn any other programming language before ?

covert bone
#

no

pseudo sierra
#

it could be sync task

#

or a recursive sync task 😄

minor wedge
pseudo sierra
#

a callback is what I said above a pointer to code to be executed later, but LATER could be RIGHT NOW...

covert bone
#

ok

pseudo sierra
#
function f(g)
{
  g();
}

function g2() { console.log(1); }
f(g2); // LATER is RIGHT NOW
covert bone
#

yesterday my mind went away like a balloon flys into the sky lol

pseudo sierra
#

To be honest, I never use async in my code

#

but then I don't write NodeJS back-end 😂

#

but Promise I use

#

or just normal events or jQuery

#

In NodeJS, you have to use await / async almost everywhere 💀

#

see the keyword propagates like a virus

#

but basically it means that your code is no longer async

#

because you await all the time, so you are making your code blocked for the stuff to complete 💀

#

and therefore potentially killing performance for readability

covert bone
#

I'm sorry , i swear that im not a mean guy , i just used to my friends's way of explanation like Malasai , norob , mellow and Maarifa

pseudo sierra
#

watch the 2 YouTube videos or similar ones that I posted, it's well explained 😉

mint thicket
keen kestrel
keen kestrel
keen kestrel
covert bone
#

we didnt reach async await yet , we only learned the basics of callback functions and yesterday it was promise @keen kestrel

minor wedge
covert bone
#

ok

minor wedge
#

Here's an analogy:

You order a pizza and you tell the restaurant: Here’s my number, call me when it’s ready.

  • You (the main program) start an action (ordering pizza).
  • The restaurant (the other function) doesn’t call you right away - it calls you later, when the pizza is done.
  • Your phone number is like the callback function - it’s a way for them to reach you when they’re done.
covert bone
#

i think that one i understood like 90%

minor wedge
#

The callback here is the callCustomer. When the pizza is ready, the customer will be called.

covert bone
#

this is lil bit more in depth , i made some simple exercises like :

function firsttemplate(getnumber) {
  return getnumber;
}

function secondtemplate(getanothernumber) {
  return getanothernumber;
}

function getlasttwo(getnumber, getanothernumber) {
  console.log(firsttemplate(5) + secondtemplate(5));
}

getlasttwo(firsttemplate, secondtemplate);
minor wedge
#

It's not much less complicated that what I did. If what confuses is the timeout I can remove it

#
function orderPizza(callback) {
  console.log("🍕 Ordering pizza...");
  preparePizza();

  console.log("✅ Pizza is ready!");
  callback();
}

function callCustomer() {
  console.log("📞 Calling customer: 'Your pizza is ready for pickup!'");
}

// Place the order
orderPizza(callCustomer);
covert bone
#

its not the i dont know what settimeout is , we only used settimeout like setTimeout(someFunction,timer);

covert bone
minor wedge
#

I see, well in this case I used an anonymous function but it's essentially the same thing. Anonymous function are functions that are not binded to a name.

covert bone
#

yea , arrow

minor wedge
#

Arrow function is a type of anonymous function. I'd rather you call them anonymous function than arrow function.

#

But they are essentially the same thing. The reason why I want you to think of them as anonymous function rather than arrow function is to make you understand a bit more the underlying concept rather than the javascript concept

covert bone
#

its just like that because we dont declare a name for the function

minor wedge
#

You really need to think about and treat functions as ordinary data, like integers, double, string, etc. You can bind them to variables, you can pass them as parameter, return them as value, etc.

covert bone
#

in the basics i get it but there is a tricky question that i need to solve , that is involving function within a function within a function

minor wedge
#

Okay, well if you want some help with that just send it here.

covert bone
#

but as you know me my dear friend , only guidance ❤️

#

Create a function that receives another function and executes it (inside its body).
Then, create another function that receives the first function and executes it.

#
function parent(childfunc) {
  childfunc();
}

function getfirst(parent) {
  parent();
}

getfirst(parent);

this is how i tried to fix it

minor wedge
#

Okay, good you're on the right track. What do you think is missing?

  1. parent -> receives another function and executes it.
  2. getFirst -> receives the first function (parent).
  3. ... Now, what does parent need in order to work correctly inside getFirst?
covert bone
#

you mean , one of those or what is missing in each thing ?

minor wedge
#

The last part.

covert bone
#

to be honest this is how our teacher wrote the exercise , he didnt ask to print something

minor wedge
#

I know but have you tried to execute this? What would happen if you execute this?

covert bone
#

childfunc is not a function

minor wedge
#

Mmh you excuted it right haha. Why do you think it does that?

#

It might help you to change names a bit

thorny eagle
#

i did that too but i think at i need to gve the first function annonimus function
i tryed it but its gave me an error

minor wedge
#
function parent(parentCallback) {
  parentCallback();
}

function execute(callback) {
  callback();
}

callback(parent);

This will cause the same error but with parentCallback. Why is that?

covert bone
#

because i didnt pass any value into it ?

minor wedge
#

What value does it need?

covert bone
#

but why ? he didnt asked us to pass any value or print something

minor wedge
#

You're right, he said "execute it". If you don't pass anything it will always cause an error

#

What is the "minimum" value you could pass to execute it?

#

Or is there more instructions that you teacher gave?

covert bone
#

i can pass anything , even MOSES idk

minor wedge
#

In the execute (getFirst) function, we pass the parent function. The parent function requires what kind of param?

function parent(parentCallback) {
  parentCallback();
}
thorny eagle
#

anonimus function maybe ?

covert bone
#

itay already saw the solution of the teacher and he saw that used arrow function

#

i dont want to see it , you know me @minor wedge

minor wedge
thorny eagle
#

i tryed it but its not working

covert bone
#

I meant that i dont want to see the teacher's solution like itay saw

minor wedge
covert bone
#

he just told me that he used arrow function

minor wedge
#

(I'm pretty sure I know your issue with arrow func XD)

covert bone
#

tbh i cant remember the syntax of arrow functions

minor wedge
covert bone
#

but wait

#

you said that i need to pass it , you didnt said that is an arrow function

thorny eagle
#
      function activateFunk6(someFunk) {
        someFunk(() => console.log("600"));
      }

      function activationFunk6(someFunk6) {
        someFunk6();
      }

      activationFunk6(activateFunk6);
minor wedge
covert bone
#

should i see it ?

minor wedge
#

No it's for Itayk and it's not the same problem as you

#

I don't want to spoil you the solution XXD

covert bone
#

it is acutally , same question

minor wedge
#

I know but the reason why your code and his code doesn't work is not the same

covert bone
#

❤️

#

ok ill go to smoke a cig , finish with itay first i guess

#

please stop with that cause itay already angry on me that im smoking lol

minor wedge
#

I will not

covert bone
#

i love you bro @minor wedge 😛

minor wedge
#

Have you look up how to define arrow function?

covert bone
#
const someFunc = (VALUE) => {
SOMETHING HERE;
};```
minor wedge
#

Make it anonymous

#

And does it need a value?

thorny eagle
minor wedge
covert bone
minor wedge
#

This would work ||I just switch the name of the functions||

||```js
function activationFunk6(someFunk) {
someFunk(() => console.log("600"));
}

function activateFunk6(someFunk6) {
someFunk6();
}

activationFunk6(activateFunk6);


There's one thing you could change too. ||Like NugByte said, you don't have to print anything. How can you make your arrow function not return anything?||
#

@thorny eagle

covert bone
#

im allowed to cry here ?

minor wedge
#

Show me the three main ways to define anonymous function (a function without name)?

covert bone
#

googling... 🙂

minor wedge
covert bone
#

expression , arrow , iifes

minor wedge
#

SHOW ME

#

Talk is cheap, show me the code

  • Linus Torvalds
covert bone
#

EXPRESSION:

    const sayHello = function() {
        console.log("Hello, world!");
    };
    sayHello(); // Call the anonymous function via the variable```
#

ARROW:

 const add = (a, b) => a + b;
    console.log(add(2, 3)); // Output: 5

    // For multi-line bodies, use curly braces:
    const greet = (name) => {
        console.log(`Hello, ${name}!`);
    };
    greet("Alice");```
thorny eagle
minor wedge
#

Can you just do

function() {
  
}

() => undefined

() => {
  
}
#

Is this valid js code?

#

Could the @cold rose work?

covert bone
#

for me , without inserting anyting , its bilnd haha

minor wedge
#

bilnd?

cold roseBOT
#
Program Output
/home/wandbox/prog.js:1
function() {
^^^^^^^^

SyntaxError: Function statements require a function name
    at wrapSafe (node:internal/modules/cjs/loader:1378:20)
    at Module._compile (node:internal/modules/cjs/loader:1428:41)
    at Module._extens
covert bone
#

yea i think it would pass

#

ohh

#

i didnt see the undefined

minor wedge
covert bone
#

ok it make sense..

minor wedge
#

You can use function() but you can't just define it randomely. You need to pass or bind it for it to work.

thorny eagle
#

how do i cover my code?

covert bone
#

btw Malassi , you want me or itay to open another ticket so it could be more clean and easy for each other ?

minor wedge
#

Maybe XD

covert bone
#

awesome , we will do that bro

minor wedge
thorny eagle
#

||```JS
function activationFunk6(someFunk) {
someFunk(() => console.log("600"));
}
function activateFunk6(someFunk6) {
someFunk6();
}

  activationFunk6(activateFunk6);
covert bone
#

Ok , itay will stay here

minor wedge
covert bone
#

I opened for me a new one

minor wedge
#

Oh

thorny eagle
minor wedge
#

Honestly, in this context, the only purpose of doing this that way is to teach you about callbacks.

#

That said, there is some real cases where you could stumble on this pattern

thorny eagle
#

I know this is for educational purposes
But is this how the solution should be?
Isn't it supposed to be a function that calls a function that does an action?

#

I think I understand
Thanks for the help

minor wedge
#

According to what Nugbyte sent me, that's what you want to do and it basically doesn't return or do anything

#

In your case you're printing 600 but it shouldn't

#
function activationFunk6(someFunk) {
  someFunk(() => { });
}

function activateFunk6(someFunk6) {
  someFunk6();
}

activationFunk6(activateFunk6);

It should look like this

#

See here, I changed the way the arrow function is written. I added an empty body.

cold roseBOT
#
minor wedge
#

It compiles and run but it doesn't do anything

thorny eagle
#

ok i will fix it

minor wedge
#

The exercice was "Create a function that receives another function and executes it (inside its body).
Then, create another function that receives the first function and executes it." right?

#

That's what nugbyte sent me. If so, it should be the solution

#

Well done!