skip to Main Content

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


  1. 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 call test("THis is addition", add, 12, 12).

    function add(a, b) {
        console.log(a + b);
        return a + b;
    }
    
    function test(testname, callbackfunction, m, n) {
        console.log(testname);
        return callbackfunction(m, n);
    }
    
    console.log(test("THis is addition", add, 12, 12));
    
    Login or Signup to reply.
  2. That’s because your function ‘test’ isn’t returning anything. you have to return from test funtion too. correct code

    function add(a,b)
    {
        console.log(a+b);
        return a+b;
    }
    function test(testname,callbackfunction,m,n)
    {
        console.log(testname);
        return callbackfunction(m,n);
    }
    console.log(test("THis is addition",add,12,12));
    Login or Signup to reply.
  3. console.log will show undefined whenever you pass anything that evaluates to undefined to it. test merely calls your callback function, but does not return it, therefore test evaluates to undefined when you pass its result to console.log. If you do not console.log its result, you won’t get undefined:

    function add(a,b)
    {
        console.log(a+b);
        return a+b;
    }
    function test(testname,callbackfunction,m,n)
    {
        console.log(testname);
        callbackfunction(m,n);
    }
    test("THis is addition",add,12,12);

    But, maybe in this example it makes more sense to return the evaluated callback function and console.log the result:

    function add(a,b)
    {
        return a+b;
    }
    function test(testname,callbackfunction,m,n)
    {
        console.log(testname);
        return callbackfunction(m,n);
    }
    console.log
    (test("THis is addition",add,12,12));
    Login or Signup to reply.
  4. You have to return the result in the function test:

    function test(testname,callbackfunction,m,n)
    {
        console.log(testname);
        return callbackfunction(m,n); // <<------- forgot to return
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search