#Callback Functions - JS
1 messages · Page 1 of 1 (latest)
search for JavaScript closure
Can you try to explain how you understand callbacks in your own words?
JavaScript Simplified Course: https://javascriptsimplified.com/?utm_source=youtube&utm_medium=video-description&utm_term=video-id-47SPG8TvUXA
FREE JS Array Methods Cheat Sheet: https://webdevsimplified.com/js-array-methods-cheat-sheet.html
FREE JS DOM Traversal Cheat Sheet: https://webdevsimplified.com/js-dom-traversal-cheat-sheet.html
FREE JS D...
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
);
wait wait wait @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
we're just learned the basics and yesterday we learned about promise
OK 😄
@minor wedge now , callback functions uses basically for async tasks , and its the abiility to call a function from another function with parameters
Did you learn any other programming language before ?
no
It's somewhat okay for a basic understanding of callbacks. The main point to change is that it's not exclusively for async tasks. It's more general than that.
a callback is what I said above a pointer to code to be executed later, but LATER could be RIGHT NOW...
ok
function f(g)
{
g();
}
function g2() { console.log(1); }
f(g2); // LATER is RIGHT NOW
yesterday my mind went away like a balloon flys into the sky lol
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
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
watch the 2 YouTube videos or similar ones that I posted, it's well explained 😉
Callbacks basically mean passing a function as an argument to another function that will call it. That another function can call the passed function argument immediately or at a later time as fd26 mentioned.
A callback is a function you pass into another function so that the other function can call it, either right away or later, depending on how it’s designed.
It is basically what it meant, a « callback ». Think of it like giving someone your phone number and asking them to call you when they’re done with something.
I just re altered what mellow said here^
Something to check here: do you understand what async is/does?
we didnt reach async await yet , we only learned the basics of callback functions and yesterday it was promise @keen kestrel
Think of it simply: a callback is a function that you pass as an argument to another function, so it can be called later when needed.
ok
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.
i think that one i understood like 90%
function orderPizza(callback) {
console.log("🍕 Ordering pizza...");
// Simulate time for the pizza to be prepared
setTimeout(() => {
console.log("✅ Pizza is ready!");
callback(); // call you (the customer) when it's ready
}, 3000);
}
function callCustomer() {
console.log("📞 Calling customer: 'Your pizza is ready for pickup!'");
}
// Place the order
orderPizza(callCustomer);
The callback here is the callCustomer. When the pizza is ready, the customer will be called.
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);
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);
its not the i dont know what settimeout is , we only used settimeout like setTimeout(someFunction,timer);
btw i fixed it alone and my friend told me , that's great
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.
yea , arrow
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
its just like that because we dont declare a name for the function
Do you understand a bit more callbacks or you are still confused about them?
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.
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
Okay, well if you want some help with that just send it here.
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
Okay, good you're on the right track. What do you think is missing?
- parent -> receives another function and executes it.
- getFirst -> receives the first function (parent).
- ... Now, what does parent need in order to work correctly inside getFirst?
you mean , one of those or what is missing in each thing ?
The last part.
to be honest this is how our teacher wrote the exercise , he didnt ask to print something
I know but have you tried to execute this? What would happen if you execute this?
childfunc is not a function
Mmh you excuted it right haha. Why do you think it does that?
It might help you to change names a bit
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
function parent(parentCallback) {
parentCallback();
}
function execute(callback) {
callback();
}
callback(parent);
This will cause the same error but with parentCallback. Why is that?
because i didnt pass any value into it ?
but why ? he didnt asked us to pass any value or print something
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?
i can pass anything , even MOSES idk
Nah you can't pass anything
In the execute (getFirst) function, we pass the parent function. The parent function requires what kind of param?
function parent(parentCallback) {
parentCallback();
}
anonimus function maybe ?
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
Didn't send anything you didn't know; I'm not showing the solution. The code above is what you have
i tryed it but its not working
I meant that i dont want to see the teacher's solution like itay saw
How did you write it?
he just told me that he used arrow function
How do you define arrow function?
(I'm pretty sure I know your issue with arrow func XD)
tbh i cant remember the syntax of arrow functions
Google it
function activateFunk6(someFunk) {
someFunk(() => console.log("600"));
}
function activationFunk6(someFunk6) {
someFunk6();
}
activationFunk6(activateFunk6);
||Your problem is the order of your calls. Try: activateFunk6(activationFunk6) instead||
should i see it ?
No it's for Itayk and it's not the same problem as you
I don't want to spoil you the solution XXD
it is acutally , same question
I know but the reason why your code and his code doesn't work is not the same
❤️
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
I will not
i love you bro @minor wedge 😛
Have you look up how to define arrow function?
const someFunc = (VALUE) => {
SOMETHING HERE;
};```
but i dont need to activate the function that call the function ?
||my point is that you mixed up the calling order. You could change the names if you want to call it with the order you want||
let x = function(){
// operations
};```
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
Nop.
im allowed to cry here ?
Show me the three main ways to define anonymous function (a function without name)?
googling... 🙂
Do you understand @thorny eagle ?
expression , arrow , iifes
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");```
i try to see i i fully understand
How would you pass an anynmous function without needing to assign it to a variable?
Can you just do
function() {
}
() => undefined
() => {
}
Is this valid js code?
Could the @cold rose work?
for me , without inserting anyting , its bilnd haha
bilnd?
;compile
/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
This is just so it doesn't crash because it has nothing
ok it make sense..
You can use function() but you can't just define it randomely. You need to pass or bind it for it to work.
how do i cover my code?
btw Malassi , you want me or itay to open another ticket so it could be more clean and easy for each other ?
Maybe XD
awesome , we will do that bro
You mean hide it? Like this:
||```
...
```||
||```JS
function activationFunk6(someFunk) {
someFunk(() => console.log("600"));
}
function activateFunk6(someFunk6) {
someFunk6();
}
activationFunk6(activateFunk6);
Ok , itay will stay here
Here's ways you can pass an anonyous function as a callback
function execute(callback) {
callback()
}
execute(function() {
})
execute(() => {
})
execute(() => undefined)
I opened for me a new one
Oh
What is the point of the function activateFunk6 if I call activationFunk6 directly?
The goal is for me to call activateFunk6 so that it activates activationFunk6, right?
Completing the exercise XD
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
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
Yep and with the last version that's what you have
You have 2 functions, that takes a function in parameter. One takes the first one and execute it
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.
;compile
It compiles and run but it doesn't do anything
ok i will fix it