Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How Java script engine handles Callback and how does the engine know that it is a callback if we pass a function as a parameter to another function.
Oversimplifying, functions are something we can pass around, like anything else. We can pass parameters that are numbers, functions, strings, etc.
Take a look at this:
// We'll just call the function passed in our function
// This is essentially a callback that does no work before
// calling the callback.
function call_function(f) {
return f();
}
var func = function(s) {console.log('func was called');}
var notAFunc = 42;
call_function(func); // func was called
call_function(notAFunc); // TypeError: number is not a function
The TypeError is the same as trying to call 42 as a function (because that's all we're doing):
42() // TypeError: number is not a function
The basics are that JavaScript doesn't do anything extra special to know if a callback you're passing is a function or not. At some point it will try to call the function, which may or may not result in an error.
EDIT
Xufox noted in a comment that the type of the paramenter could be checked, something like this:
function call_function(f) {
if (typeof f === 'function') {
return f();
}
}
It's good to keep that in mind, but that has nothing to do with the engine, it's up to the programmer to do that kind of sanity checking.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
While in VS Code, I hit the tab after typing return and the VS Code Intellisense auto-completed "return" to "this.return".
I've never seen this before and cannot find any documentation on it.
Does anybody know if this is actually a thing, or if VS Code possibly lost it's marbles.
Note: the object I was working in does not have any properties or functions called "return".
Well, an object could have a property called return:
const obj = {
return: () => { console.log('↩️'); }
};
obj.return();
Were you in the context of a class that had a return property, or maybe its superclass did?
(Honestly it seems more likely VS Code was just being weird.)
You can run console.log("this", this) in most modern browsers this will return the JSON data of this (the variable this refers to the current instance of declared object FYI), and console.log(typeof(this.return)) and it will likely return function (if you get undefined just change it from this.return to return;)
Likely the object either has a property called return that is a function, or something has gone wrong in the autocomplete.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to provide a callback as a parameter to a function.
The callback will be called by the function with certain parameters. But I need to add some extra variable data on each call.
So let's say the callback is: function(par1, par2, my_par=my_variable) { ...
par1 and par2 are the parameters that the function will pass when invoking the callback. And my_par is the optional parameter I need to have differnent values on each call so it can be accessed from inside the callback.
It doesn't work. How can I do it?
Thanks.
Hard to make out your actual problem since you didn't provide a working example of your problem, but this may help:
function executeTheCallback(cb) {
cb();
}
function theCallback(greeting, name = 'Anonymous') {
console.log(`${greeting} ${name}!`);
}
executeTheCallback(theCallback.bind(null, 'Hello')); // Hello Anonymous!
executeTheCallback(theCallback.bind(null, 'Hello', 'World')); // Hello World!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
let unrealFunctionToUnderstand = () => {
let tryToUnderstandThis = () => 666;
console.log('I\'m calling once time! :D');
return tryToUnderstandThis;
}
let hardcoreLesson = unrealFunctionToUnderstand();
console.log(hardcoreLesson());
console.log(hardcoreLesson());
I cant understand this code, my friend send me this...
unrealFunctionToUnderstand is a function. When called it logs "I'm calling once time! :D".
It also returns another function (tryToUnderstandThis) when called.
After defining this function you are (1) calling it unrealFunctionToUnderstand(), then (2) assigning it's returned value (tryToUnderstandThis) to hardcoreLesson. Then you are calling hardcoreLesson (reference to tryToUnderstandThis) twice and logging the result.
So you are calling unrealFunctionToUnderstand once, and it logs "I'm calling once time! :D", then calling tryToUnderstandThis twice, and it logs "666" twice.
Can you notice how I "ran" this code on paper? This is how you answer questions like this yourself. You interpret the code the same way the browser would, on paper. It becomes easier to pinpoint language constructs you don't understand or know yet, so you can first learn / ask about those. Then, if you understand each part, it becomes clear what is executed and why.
everything in javascript is an object, including functions. Which means you can return a function from a function.
That is exactly what unrealFunctionToUnderstand() is - it is a function which returns a function.
So, you call it once:
let hardcoreLesson = unrealFunctionToUnderstand();
Hence the console output only displays once. And you now have a reference to a function which simply returns the value 666.
let tryToUnderstandThis = () => 666;
....
return tryToUnderstandThis;
When you execute that, you get back the response.
hardcoreLesson store the value return by this function unrealFunctionToUnderstand.
So unrealFunctionToUnderstand calling only one time.
as hardcoreLesson store the value it's shows 2 times as it's called two time.
If you are familiar with any other programming language like C or Java, then you will be familiar with the following syntax.
function functionName(argument1, argument2, ...) {
// function body
// return statement
}
The new version of javascript introduces the arrow operator => to reduce your effort of writing single line functions. This is similar to lamda/inline function used mostly for single line functions.
So if you have a following function
function increment (value) {
return value + 1;
}
you can replace it with
increment(value) => value + 1
The other answers should help you understand how the function are also objects and how it can be called in different ways.
Some helpful links
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Had this problem already several times: I've got to program a function in JavaScript.
In know how to check if the required parameter has been assigned. I also know how to check data-type correction.
When one of the checks fail I like to terminate the function by using return.
The thing I'm unsure about: What value shall I return in case of failure?
Some people use 0 or -1 ...
I've seen people doing something like ...
if (x === undefined) return
... what results in the return of undefined.
Or shall I throw an exception instead of using a return?
The return value has no meaning until you decide to handle it. This means you can make them whatever you like, as long as you are handling them accordingly from the other side. for example:
function foo(){
if(goodstuff){
//do good stuff
}else{
return 1;
}
}
Returning 1 here doesn't inherently mean anything. 1 or -1 are simply common return values for an error. The key is for you to handle the "error" when the function is called:
var success = foo();
if( success === 1){
alert('error');
}else{
//do stuff
}
you can return false, null, 0, "oopsies" or whatever other value makes sense for your situation. The only thing that matters is that you handle it accordingly. Generally returning false or 0 makes for the simplest check, which is why they are commonly used.
To answer your other question, simply doing return; will just terminate the function without sending back a value. This is useful if you don't necessarily need to return an error code, but simply just don't want the rest of the code in the function to execute. For example:
function bar(){
if(notAWinner){
return;
}
alert('you win a million dollars!');
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was reading Chapter 4: Functions() of the book Javascript Enlightenment by Cody Lindley.
http://jsfiddle.net/4a860dkg/
I was playing around with functions and wanted to know why in the fiddle addNumbersA returns anonymous(num1, num2, /**/) rather than returning a function()
Can anyone tell me why does this happen?
EDIT:
1. What I want to ask is that why doesn't logging addNumbersA return me a function() as it must do.
2. When I use typeof(addNumbersA), I get a function and not a function() - whereas addNumbersB returns function().
Apologies if i'm not clear enough.
The reason console.log(addNumbersA); returns:
function anonymous(num1,num2
/**/) {
return num1 + num2
}
Is because its a functional expression. The function keyword, when used as an expression, can create a function value. A function value can do all the things that other values can do—you can use it in arbitrary expressions, not just call it. It is possible to store a function value in a new place, pass it as an argument to a function, and so on.
Similarly, console.log(addNumbersB); returns:
function (num1, num2) {
return num1 + num2;
}
You can test this out in chrome dev tools, perhaps some inspectors/js repls have different notations of shortcutting, such that you may not get EXACT output (ie. just get 'function()' in Firebug).
Function is a constructor for function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
When you define a function as an instance of Function constructor, it is not compiled but stored as a runtime string. That's why it shows up as a function definition and not as a function object.
They will function the same except because it is compiled at the time of execution, it only has the global closure and has no knowledge of the local closure except for its own local variables.
console.log(addNumbersB); // logs function() correct!
This will not run the function, which your are expecting.
This does:
console.log(addNumbersB(2,2)); // logs 4 correct!
The above returns 4 because we call the function and pass the two numbers which are then added by the function;
The first example you give is a method rarely used for normal day to day coding, it creates a function from a string that represents valid code.