Nested call to function in Javascript - javascript

Intellij IDEA shows a warning when ever I write Javascript like this:
someFunction(someOtherFunction());
But the explanation is not really helpful:
"This inspection reports any Javascript function calls used as
arguments to another function call."
This is something I do frequently, so what's the potential trap hiding there worth warning of? Or if it's just some coding convention, what's the reason for it?

It is a warning because most of the time, you want to pass a function reference as an argument. It is mostly used as a callback:
someFunction(someOtherFunction);
function someFunction(fn){
fn.call();
}
In that example, someOtherFunction() instead of someOtherFunction would not work as expect (unless someOtherFunction returns a function itself).
someFunction(someOtherFunction()); work more like a getter.
someFunction(someOtherFunction());
function someFunction(int){
alert(int === 1);//True;
}
function someOtherFunction(){
return 1;
}
It gives a warning because it is a common mistake for new developers.

Related

Determine function file/line location given reference in NodeJS?

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());

Javascript callback functions differences

I would like to know the difference between 2 implementations of callback functions.
This:
$("#button").on('click', function () {
//do something
});
Versus having the function already defined.
$("#button").on('click', btnFunction);
function btnFunction() {
//do something
}
Are there any implications with one compared to another? Performance-wise is one faster?
The first uses an anonymous function and the second does not. There's no difference in both.
See:
Why do you need to invoke an anonymous function on the same line?
Some folks prefer the second form because it gives a function name when using the debugger and tracing, but there are ways to get the same functionality in the first form.
If you are attaching and removing the event handler based on changing conditions, the second form is much easier to maintain, however.
There's no difference at all, and there's no performance issue with neither one of them. The only difference is that in one of them you're defining the callback function as an anonymous function, this way you cannot reuse it.
The other way, where you define it else where and named it and then pass it as a callback, you're defining a function that you can later reuse in another part of your code.
For example: if you want to do something when the document is ready, and then do se exact same thing when some one press a button you can use something like this:
function getData() {
//do something
}
$(function() {
// Call the function once the DOM is ready
getData();
});
// Call the same function when the button is clicked
$("#refresh_button").on('click', getData);
In most cases the first one will be used, called Anonymous Functions
The second one will be used when the function is not only used inlined here, but also needs to be reused somewhere else.
But anyway it could be a personal preference.
The only real difference you could see is that stack trace (if an exception is thrown for example) will be better, i.e. easier to debug, when using the second one.
Just reuse-ability.
In the second case, you could call btnFunction() somewhere else if need be.

Different functions - are they the same?

I'm a JavaScript slightly-more-than-beginner.
While reading the source for EventEmitter, I stumbled upon this interesting and, to me, elegant function:
// alias a method while keeping the correct context
function alias(name) {
return function aliasClosure() {
return this[name].apply(this, arguments);
};
}
I have two main questions:
First: why is the aliasClosure a named function? Is it useful in some way other than clarity? Also, is is really a closure? To me, it looks just like a semi-anonymous function.
Second: I rewrote this function like this:
function alias2(name) {
return this[name].bind(this);
}
Is it equivalent? I think it should, since the this context is the same and it's preserved in both versions.
Is there a reason to prefer one over the other?
No, these are not at all equivalent. From looking at the alias() function I think you would use it something like this:
> Array.prototype.strjoin = alias('join'); // make 'strjoin' an alias of 'join'
> [1, 2, 3].strjoin(" + ");
"1 + 2 + 3"
Using alias2() in the above code will not work.
Providing a name in a function instantiation expression makes a name available for stack traces. (I'm told newer debuggers don't always need it if the function is created in certain contexts, like a var initialization.)
I think the second is equivalent, mostly, though .bind() has some obscure special cases it handles.
edit wait - no, they're not equivalent. The first one involves this explicitly, and performs the lookup on each call. The first function doesn't need this to be bound to anything when it's called, while yours will throw an exception in that case.
One change that would make the two functions almost equal is wrapping bind inside a closure, like this:
function alias2(name) {
return function() {
return this[name].bind(this);
}
}
Still, bind behaves obscurely in rare cases.

Only call constructor behaviour if particular function isn't called

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.

Unit testing a function that does not return anything in Javascript

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.

Categories