I have been learning javascript test scripts in Postman.Here I am just learning about callback functions and I wanted to check return value is showing in the last line of print statement but the result shows ‘undefined’. Below is the code:
function add(a,b)
{
console.log(a+b);
return a+b;
}
function test(testname,callbackfunction,m,n)
{
console.log(testname);
callbackfunction(m,n);
}
console.log
(test("THis is addition",add,12,12));
Console shows:
THis is addition
24
undefined
Why it showing undefined in the last line instead of showing 24 the return value?
Thanks in advance.
I tried to store the return value in a variable but it showing the same ‘unfined’ result.
let stu=test("THis is addition",add,12,12);
4
Answers
The issue is that your test function isn’t returning anything. In js if a function doesn’t return a value it automatically returns
undefined
. So, when you calltest("THis is addition", add, 12, 12)
.That’s because your function ‘test’ isn’t returning anything. you have to return from test funtion too. correct code
console.log
will show undefined whenever you pass anything that evaluates toundefined
to it.test
merely calls your callback function, but does not return it, thereforetest
evaluates toundefined
when you pass its result toconsole.log
. If you do notconsole.log
its result, you won’t getundefined
:But, maybe in this example it makes more sense to
return
the evaluated callback function andconsole.log
the result:You have to return the result in the function
test
: