I am trying to invoke a function within a function which is not a big deal but for some reason i don't understand why i can't invoke a function through this logic:
function func1(futurefunc){
futurefunc();
}
function func2(){
return 3+3;
}
func(func2);
Now the result of the code above is undefined. However when I put: func(alert), the alert argument is invoked. I don't understand why is the second case running and the first part is not printing the returned value which in this case would be 6.
However when I try the following:
function func1(futurefunc){
return futurefunc();
}
the code seems to serve the proper value, which is 6 in this case. Any clear explanation. I hope I am not missing anything.
The first case, func1 just invoke futurefunc() and doesn't return anything so undefined is printed.
When you passed, alert, alert is invoked then you see the dialog.
The second case, func1 invoke futurefunc and return its result, so 6 is printed.
There is nothing hard to understand here.
Related
The fact that I can't think of how to do this makes me think it's some sort of anti-pattern, or impossible. If anyone has any better ideas of how to handle my situation, recommendations always welcome.
I have a legacy codebase and at one point I am retrieving function references and calling the function. These function calls are expected to return a result, but sometimes they are missing their return statement. Currently I throw an error if the returned value is nullish but this only gives me a stacktrace to the engine location that is calling the function, not the function itself.
Is there any way that I can determine the file name/number of the function, or force the function to throw an error such that a stacktrace to that actual function is generated?
There is no such feature in the Javascript language. It's not anti-pattern, just not something that the language supports. There is no requirement that a function have a return statement and there is no way to force it to throw an exception if it doesn't return a value.
Without seeing any of the relevant code, I can offer some suggestions:
Set a breakpoint at the line of your code that initiates the function call. Then, trace into the function in the debugger. You can go as far into it as you need to and each time you go step into a new function call, it will show you the file and line number that you're on. I use this technique regularly when I'm confused by some behavior by some module (either built-in to nodejs or an external module I'm using) and it's not immediately clear how to find the right code on Github for it. I just step into it and can immediately see the code and watch it execute line by line as needed for whatever problem I'm investigating.
Assuming this function you're calling expects some arguments, you can give it some sort of bogus arguments that would hopefully trigger it to throw some sort of exception and you could then see the stack trace from that exception. For example, if it was expecting a non-optional object as an argument, you could pass null and see if that triggers an exception. If it was expecting a callback, you could pass a non-function and see if that triggered an exception.
As for the name of the function, if the function has an actual name (it's not anonymous) and fn is your function reference, then you can do console.log(fn.name) and see if there is a name. You could also examine fn.toString() and see if it reveals the source code of the function. Sometimes it will and if the function is a named function that may show you its name. This won't show you what file it's in, but you could perhaps then grep for something you see in the source to find it.
Here's an example from point #3:
function hello() {
return "hi";
}
// create function reference that points to my function
const fn = hello;
// log info on that function reference
console.log(fn.name);
console.log(fn.toString());
When I use something like
if(asynchronous.get()){...}
And ansynchronous.get() is an asynchronous function, I wonder how this could ever work as the if statement isn't testing anything unless the function returns a value. Somehow I have this in my code and it works so can anyone explain to my why it works and if I should change it.
Edit: My assumption that my function is asynchronous was wrong, so everything is answered now.
The if statement simply checks if the expression evaluates to a truthy value. It seems the function returns a promise, which is a function object, which is a truthy value.
The function will be executed, but you will not be able to process the result this way and the if statement will never be evaluated to false.
You need to wait for the function to resolve a value and then check the value:
asynchronous.get().then(val => {
if (val) {...}
})
Apologies - I have no idea to how to describe this. Example:
function OutputNumber(number) {
this.outputThisInstead = function (otherNumber) {
console.log(otherNumber);
}
console.log(number);
}
Desired usage:
new OutputNumber(1);
Console output: 1
new OutputNumber(1).outputThisInstead(2);
Console output: 2
Naturally, 1 will always be written to the console, irrespective of what else is called on the object.
I'm after this particular syntax, as well as the behaviour - attaching a function onto the initialisation. It feels impossible since the object must be constructed before any function is called on it, but is this achievable any other way?
It would be possible with a time delay (e.g., in a browser environment, setTimeout or similar) and a flag. Not desirable, but possible.
Without that, no, you can't base the action of the constructor on something that hasn't happened yet. You'd have to instead pass something into the constructor to let it know what was going on.
Browser example (again, I don't recommend this):
function OutputNumber(number) {
var handle = 0;
this.outputThisInstead = function (otherNumber) {
if (handle) {
clearTimeout(handle);
handle = 0;
}
console.log(otherNumber);
}
handle = setTimeout(function() {
console.log(number);
}, 0);
}
From your comment on the question:
This is the end of a sequence of chaining objects/functions, that I'm experimenting with. For example:
Assert.that(1).is.not(2).because('output this message if fails');
Here not(2) returns an object on which because can optionally be called. The behaviour of the object would depend on because being called.
Rather than have the behavior of an earlier function in the chain depend on a later function in the chain, I'd probably add an .end() at the end of something:
Assert.that(1).is.not(2).because('output this message if fails').end();
end would output whatever message/messages was/were stored by the previous functions. No need for black magic. Obviously this suffers from the fact that people could fail to put the .end() on, but you need some kind of trigger that it's okay to do the output, if you want the output to change based on an optional subsequent function call.
Not possible. By the time you do new OutputNumber(1) the function has already been called. A chained method will have no access to its preceding call.
It's possible to declare outputThisInstead as "static":
function OutputNumber(number) {
console.log(number);
}
OutputNumber.outputThisInstead = function (otherNumber) {
console.log(otherNumber);
}
new OutputNumber(1); //1
OutputNumber.outputThisInstead(2); //2
But if you want to create an object with the new operator the function will always log the number parameter.
You can also achieve similar behavior to the one you want with partial apply of the function (here). This is also called Currying or Schönfinkeling. The idea is that you can fill the function's parameters one after another and when the full set of parameters is available the function is being executed. You can see a currying example here.
This block of code always returns errors:
eval('if(!var_a){return 0;}');
A statement like this works perfectly fine:
eval('alert(1)');
A JavaScript statement such as eval('return 0') always gives an error when its intention is to make the script stop further execution.
eval simply gives unwanted errors when it is run in some block of code and a return statement is in it.
This is because you are using return outside of the context of a function. Wrap your code in a function and return works fine. There are a few ways to do that. I suggest that you do not use any of them. Instead find a way to avoid eval. Regardless, here are some solutions:
eval('(function() { if(!var_a){return 0;} })()');
or
new Function('if(!var_a){return 0;}')()
You can only return from within a function. Like so:
function foo() {
if (x) alert("woo");
else return 0;
doMoreStuff();
}
You're not in a function, so there's nothing to return from. Also, why are you using eval at all?
In the first case, you are attempting to execute an expression with a return. In the second case, you are calling a function that returns a value. To do what you want, you can declare and invoke an anonymous function within the expression as follows...
eval('(function(){ if(!var_a){return 0;} })()');
Of course, if the question is just how to construct an evaluateable expression that includes a condition, you can use the "ternary" operator...
eval('var_a ? nil : 0');
As topic suggested, how can I unit test a function that does not return anything (apart from null checks that simply returns)?
And also, how do I unit test the functions within a function which also does not return anything especially if they are at the last lines of a function?
The reason behind this question is that I've been trying to use Jack and JsMockito to test my code, and they all required me to provide some sort of object which seems to be returned by a function in the code, hence I'm lost on how to do so.
Thanks.
EDIT:
Here is a sample pesudo code:
function myFunction()
{
local var
null check {
return;
}
null check
{
return;
}
// points to another function
function(param1);
// points to a C# function
function(param1, param2);
}
Surely your function must have some effect or change to the system/program, that can be detected/compared outside the function.
If it does nothing => delete the code, you don't need it!
If it is meant to throw errors, try to catch them (make calls containing know wrong parameters/conditions, then see if they are caught.
You need to work out what the side effects of the function are, then test that they happen.
The code above calls two other functions. So your unit test would validate that they are called, most likely by mocking them in some way.