I wonder why this simple callback function (setTimout) gets called even though I didn't invoke but just assigned it.
In this code, I assinged setTimeout function to variable foo.
So I believe a returned value should be stored in variable foo
And It doesn't need to be executed and print 'hello' because I didn't call that function.
But why It gets called and print 'hello'?? What if I just want to assign and store it to variable??
Also How this function can be a number type and returned value is 2 ??
const foo = setTimeout(() => console.log('hello'), 2000);
// hello ( after 2 seconds )
console.log(typeof foo);
// number
console.log(foo);
// 2
Thanks in advance
To declare it a function to be called later:
const foo = function () {
setTimeout(() => console.log('hello'), 2000);
}
The return value of setTimeout is an integer Id for the timeout that can be used later with clearTimeout();
e.g.
var t = setTimeout(() => console.log('hello'), 2000);
// clear the time out
clearTimeout(t);
setTimeout invokes it. That's why it's called a callback. Another more common word for "invoke" is "call" so a callback is basically an invokeback: someone will invoke your code later.
Here's an example of code that accept a callback:
function foo (cb) {
// this function prints "foo" if callback returns true
if (cb()) { // foo() invoking cb()!
console.log('foo');
}
}
As you can see, the programmer who writes the function is the one who invokes/calls your function. You just need to define the function that they are going to call:
foo(function() { return true })
You just invoked the function with two parameters and stored the return result of setTimeout
const foo = setTimeout(() => console.log('hello'), 2000);//
Example:
I have a function setTimeout1
function setTimeout1(parm1, parm2){
// do somthing
return "Invoked";
}
const foo = setTimeout1(() => console.log('hello'), 2000);
Related
I have some method of an object assigned by a decorator (that's where the function f, and ms are taken from).
function() {
setTimeout(() => f.apply(this, arguments), ms);
};
'this' refers here to the object. But 'this' of setTimeout is window, not that object. If 'this' of an arrow function is taken lexically, then how come it's not taken from setTimeout? After all, in the following code:
let user = {
firstName: "Ilya",
sayHi() {
let arrow = () => alert(this.firstName);
arrow();
}
};
user.sayHi(); // Ilya
'this' is taken from the function above. So if that function is setTimeout in the first situation why aren't both situations the same? I thought it might have had something to do with the function being passed as argument in one case, and in the other one as a local variable, but wouldn't this come down to the same in lexical environments?
Why is there a difference?
Besides, to test this out:
let obj = {name : "Jeff"};
let obj2 = {name : "Bart", fun2 : function(fun){fun();}};
obj.name2 = obj2.fun2(() => alert(this.name));
but now I don't get "Bart" alerted, but an empty string. When I replace "name" with length, I just get 0, the 'this' refers to the window.
Why doesn't this work as intended?
If 'this' of an arrow function is taken lexically, then how come it's not taken from setTimeout?
Lexical means that the scope is taken from where the function is declared, not where it is passed to.
Inside a function, the value of this depends on how the function is called.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
function f1() {
return this;
}
// In a browser:
f1() === window; // true
In your function you have passed the window object to the setTimeout.
If you alter you function and pass just arguments you will get the object:
function f() {
console.log(this);
};
function a (){
setTimeout(() => f.apply([1]), 1000); // here this = [1]
}
a(); // Array [1]
How are callback functions different from a helper function in javascript? if they are both accepting functions as arguments?
Callbacks are the functions that are passed as a function argument and are performed after a particular event such as resolving of a promise.
Helper functions are the normal functions that are called at any point of time when the code execution is taking place. Mostly, helper functions are wrapped inside another function.
Example of callback function:
const fun = (callback) => {
setTimeout(callback, 3000);
};
fun(() => {
console.log('callback function');
});
Example of helper function:
const factorialOfNNumbers = (...numbers) => {
const helperFact = (n) => {
if (n ===1 || n === 0)
return n;
return n * helperFact(n-1);
};
return numbers.map(n => helperFact(n));
};
console.log(factorialOfNNumbers(2, 3, 4));
They are both functions, but the difference I suppose is how they are referenced and/or used.
Helper functions are just called "whenever" when they are in scope. Callbacks are typically passed elsewhere and invoked with some parameters.
I hope the below snippet explains it.
// Just some function, what does it do?
const someFunction = (...args) => console.log("I'm a helper function", ...args);
const useAsHelperFunction = () => {
// Called directly
someFunction('used as helper function');
};
const useAsCallback = callback => {
// invoking callback
callback('used as callback function');
};
useAsHelperFunction();
useAsCallback(someFunction);
There nothing like callback function, it just refers to the function(named function) or anonymous function that is being called by a function or piece of code once it transitions to another state or after an event occurs.
I originally come from the Java Programming language, and I was just wondering why it is possible in javascript to pass a callback function as a variable or plain object (without parameters) to another function, and then use this callback function inside of another function but this time with parameters to pass.
And how exactly is this callback returning my user object, as I did not specify a return function inside callback(user), or specify any function body at all for my callback. Is this done inside the setTimeout(()...) function as the timeoutHandler implementation is implicitly returning something?
var getUser = (id,callback) => {
var user = {
id: id,
name: 'Vikram'
};
setTimeout(() => {
callback(user);
},3000);
};
getUser(31, (userObject) => {
console.log(userObject);
});
I see two questions here:
why it is possible in javascript to pass a callback function as a variable or plain object (without parameters) to another function.
Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
Read more here: https://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
Below shows functions are just objects as well:
function hello() {
return 'hello';
}
hello.other = 'world';
console.log(hello() + ', ' + hello.other);
how exactly is this callback returning my user object, as I did not specify a return function inside callback(user), or specify any function body at all for my callback.
setTimeout(()...) function is not implicitly returning anything, it just registers a function, that would execute later. When the function registered by the setTimeout triggers, it invokes the callback(user) and that resolves getUser registered function which logs to the console. Remember callbacks are asynchronous.
Functions have implicit returns if not specified, which returns undefined, meaning you did not explicitly return.
Below shows an example:
function hello() {
console.log('Hello, World');
}
console.log(hello()); // undefined.
function hi() {
return 'Hi, World';
}
console.log(hi()); // Hi, World.
The function i.e callback is passed as reference here. So you can pass it as much you want, when you call it then you can pass on the arguments and it will refer to original function.
And also it's not returning the user object, it's just consoling out the user object. As you have not used any return it will return undefined. Try consoling the callback fn return out.
var getUser = (id,callback) => {
var user = {
id: id,
name: 'Vikram'
};
setTimeout(() => {
console.log(callback(user), 'return value of callback');
},3000);
};
In javascript function is a object.
It behaves like function only with ()
So you can pass function to another function or variable as value.
Some functions in javascript are asynchronous.
setTimeout is such async function. It means callback function will be run after a time.
What's happening:
//assign anonymous function to variable
// until function without () it only a object
var getUser = (id,callback) => {
//set up params
var user = {
id: id,
name: 'Vikram'
};
// setup asynchronous function setTimeout
setTimeout(() => {
// run callback with params when time would done
callback(user);
},3000);
};
// call function which contains in getUser-variable and pass 2 params: int and callback-function
getUser(31, (userObject) => {
console.log(userObject);
});
I am new to programming and trying to understand callback functions and functions in general. This program compares 2 values passed in the functions(using callback) and return true/false to us.
function func1(param1, callback) {
return callback(param1);
}
function func2(param2) {
return function(param3) {
return param3 > param2;
}
}
var functionResult = func1(10, func2(9));
console.log(functionResult); // prints - true
Question - In this program above, how does the return function inside the func2 function, return the value directly to us, without being invoked? I thought in this line var functionResult = func1(10, func2(9)); func2(9) will return only the text
function(param3) {
return param3 > param2;
}
and then I would have to invoke it again with ().
how does the return function inside the func2 function, return the value directly to us, without being invoked?
It is invoked. func1 invokes it here:
callback(param1)
func2(9) will return only the text ...
That's not text, that's actually a function (object). It is passed to func1 which in turn calls it and returns its return value.
and then I would have to invoke it again with ().
Yes, which, again, is what func1 does:
callback(param1)
Lets take things apart:
var functionResult = func1(10, func2(9));
is the same as
var func2Result = func2(9);
var functionResult = func1(10, func2Result);
Since we know what func1 does, we can replace the call to it with it's implementation. 10 is passed as param1 and func2Result is passed as callback, so the code becomes:
var func2Result = func2(9);
var functionResult = func2Result(10); // callback(param1);
Now you should be able to see that the return value of func2 is actually called.
I've been learning JavaScript and AngularJS and have been seeing functions with an extra set of parentheses. What is this? How does it work?
e.g.: myFunc(args)(moreArgs).
The extra set is for running and returning another function. So, using your example: myFunc will take one argument and return a second function (can be anonymously named):
function myFunc(args) {
return function (moreArgs) {
return args + ' ' + moreArgs;
};
}
var myMsg = myFunc("This")("works!");
alert(myMsg);
In javascript a function can return a function and that returned function can be called immediately. For example:
function a () {
return function () {
console.log('hello');
}
}
One way of calling the returned function is:
var b = a(); // b is now a function returned by a
b(); // logs "hello"
But in javascript you can also do:
a()(); // calls the returned function immediately, logs "hello"