I have read callbacks are used for event handlers or in asynchronous codes where we are not sure of the response, but my question is very simple that should I use callback when I have a function to be used in another function?
For example:
let name = function () {
return "Umar"
}
let printName = function () {
return name()
}
console.log(printName())
But in the below code, I am trying to pass as a callback function, and returns synatx error. Can I use callbacks here for this case, also it is returning error.
let name = function () {
return "Umar"
}
let printName = function (name) {
return name()
}
console.log(printName())
Also I have another problem, Look at this code it is thrwoing an error for the variable to be not defined, however I have defined it
let name = function () {
return "Umar"
}
let printName = function () {
let name = name()
return name
}
console.log(printName())
However. naming varaible name as name1 in the second function works fine, for example
let name = function () {
return "Umar"
}
let printName = function () {
let name1 = name()
return name1
}
console.log(printName())
Why the name variable is throwing error even after I have defined it.
A callback is when you pass one function as an argument to another. You never do this .
In one place you almost do this:
let printName = function (name) { return name() }
Above you are written a function which calls the first argument it gets as a function.
However when you then call the function:
console.log(printName())
… you don't pass any arguments!
Consequently, name
is undefined and the function throws an exception.
Why the name variable is throwing error even after I have defined it.
You declared name
twice. Once in the global scope (where you assigned it a function) and again in the scope of the printName
function (where you assigned it undefined
).
should I use callback when I have a function to be used in another function?
Not as a general case. You use a callback when you have a function that needs to call different functions at different times.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.