JavaScript: when assigning an anonymous function to a variable, the return value of the function is not passed, and the function as a string

I am trying to learn JavaScript, but I ran into an obstacle. If the answer is obvious and accessible through a simple search, I apologize in advance. I am new to programming and JavaScript and don’t know which query line to follow.

In the following code, the function takes values ​​from an HTML form, processes and sends them back. I tested the input and output process and it works 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 that when the else branch of a conditional statement tries to process an anonymous function, the return value is not assigned; and the whole function as a string. That is, the following is displayed on 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; }}

Chrome Firefox, .

.

+3
1

, , z , :

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

, (x, y), , , , , foo.

+12

Source: https://habr.com/ru/post/1733653/


All Articles