2

I am creating a function object. However when I run this object it returns undefined.
For instance, in this JSFiddle example, when I try alert(test(8)), the function runs and returns 13 but when I create a Function object, 'alert(func(8))' returns undefined.

<button onclick="start()">Start Test</button>

<script>

    function test(num) {
        alert("running...");
        return num + 5;
    }

    function start(){
        alert(test(8));

        var func = new Function("num", "test(num)");
        alert(func(8)); 
    }

</script>

2 Answers 2

5

Because in your second func, you are not returning the value of test(num)

function test(num) {
  alert("running...");
  return parseInt(num) + 5;
}

function start(){
  alert(test(8));

  // return the value obtained on calling test(num)     <------------
  var func = new Function("num", "return test(num)");
  alert(func(8));
}

start();

Sign up to request clarification or add additional context in comments.

2 Comments

@NevilleNazerane Ok, nice you did. Could you please accept my answer if it helped. Thank you!
Well frankly I found out the exact same solution before looking at your answer. However even thought it did not help it was perfect. I will accept it as far as stackoverflow allows me to do so.
0

I found a solution. When I checked the value of the variable func in the console I found I would need to return the function like this JSFiddle. I needed to use var func = new Function("num", "return test(num)") instead of var func = new Function("num", "test(num)")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.