Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: When assigning an anonymous function to a variable, function return value is not passed, rather the function as a string

I am trying to learn JavaScript but I've come across a hurdle. If the answer is obvious and reachable through a simple search I apologize in advance. I am a novice to programming and JavaScript, and unsure what line of inquiry to follow.

In the following code, the function takes values from a HTML form, does some processing and sends them back. I've tested the input and output process and it's working correctly.

function foo() {

var x = parseInt(document.formdata.fieldone.value);
var y = parseFloat(document.formdata.fieldtwo.value);

if (isNaN(y))
    { var z = x; }
else
    { var z = function(x, y) {
            if ((y * (x / 100)) < 1) {
                return (x + Math.ceil(y * (x / 100))); }
            else if ((y * (x / 100)) > 1) {
                return (x + Math.round(y * (x / 100))); }
            else {
                return 0; } } }

var bar = document.getElementById("output");

bar.innerHTML = z; }

The problem is, when the else branch of the conditional statement tries to process the anonymous function, the return value isn't assigned; rather the entirety of the function as a string. That is, the following appears in the HTML page:

function (x, y) { if ((y * (x / 100)) < 1) { return (x + Math.ceil(y * (x / 100))); } else if ((y * (x / 100)) > 1) { return (x + Math.round(y * (x / 100))); } else { return 0; } }

I've tested the code in Chrome and Firefox and the result is the same.

Any help is appreciated and thank you in advance.

like image 832
Omega Avatar asked Feb 20 '10 10:02

Omega


1 Answers

You need to call the function by passing it two arguments, because otherwise the z variable will just store a reference to this function but it will not evaluate it:

var z = (function(x, y) {
    if ((y * (x / 100)) < 1) {
        return (x + Math.ceil(y * (x / 100))); }
    else if ((y * (x / 100)) > 1) {
        return (x + Math.round(y * (x / 100))); }
    else {
        return 0; 
    } 
})(x, y);

Note that (x, y) used inside the anonymous function are not the same as the one passed as arguments at the end which correspond to the two variables declared in the beginning of the foo function.

like image 100
Darin Dimitrov Avatar answered Sep 20 '22 13:09

Darin Dimitrov