assign function return value to some variable using javascript

javascript function return html string
javascript functions list
javascript function not returning value
how to store a function in a variable javascript
nodejs function return value
how to get javascript function return value in php variable
javascript return html
javascript return value to another function

I have a js function , after doing some business logic, the javascript function should return some result to another variable.Sample code below

var response="";
function doSomething() {  
    $.ajax({
        url:'action.php',
        type: "POST",
        data: dataString,
        success: function (txtBack) { 
            if(txtBack==1) {
                status=1;
            }
    });
    return status;     
}

Here i want to use like

response=doSomething();

I want to assign a return value "status" "var response".But the result is 'undefined'.

Or just...

var response = (function() {
    var a;
    // calculate a
    return a;
})();  

In this case, the response variable receives the return value of the function. The function executes immediately.

You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.

Function return values, After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the  Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values. Those values need to be calculated by a function, which then returns the results so they can be used in the next stage of the calculation.

AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status is undefined when it is returned.

Effectively, your code works as follows:

function doSomething(someargums) {
     return status;
}

var response = doSomething();

And then some time later, your AJAX request is completing; but it's already too late

You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.

Where you previously may have had

var response = doSomething();

alert(response);

You should do:

function doSomething() {  
    $.ajax({
           url:'action.php',
           type: "POST",
           data: dataString,
           success: function (txtBack) { 
            alert(txtBack);
           })
    }); 
};

storing results of a function in a variable, '''javascript w that you've created the returnValue function, call it, by passing it a literal string value -- a series of characters in quote marks like  For a function that doesn’t return anything useful, you could omit the return, or explicitly return null or undefined. The repeated function is a little awkward, and there are other approaches. For basic array iteration, you could use the each provided by Underscore.js or jQuery, or the forEach provided natively in recent versions of JavaScript.

You could simply return a value from the function:

var response = 0;

function doSomething() {
    // some code
    return 10;
}
response = doSomething();

JavaScript Functions, Example. Instead of using a variable to store the return value of a function: var x = toCelsius(77); If you had some variable y, it could take on the value of the function with something like: var x = function(){ return true; }; var y = x(); // y is now set to true. or alternatively execute the function in place with: var x = (function(){ return true; })();

The only way to retrieve the correct value in your context is to run $.ajax() function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async you should set to false. In that case the main scope which actually contains $.ajax() function call is paused until the synchronous function is done, so, the return is called only after $.ajax().

function doSomething() {
    var status = 0;
    $.ajax({
        url: 'action.php',
        type: 'POST',
        data: dataString,
        async: false,
        success: function (txtBack) {
            if (txtBack == 1)
                status = 1;
        }
    });

    return status;
}

var response = doSomething();

Problem assigning function result to variable, Problem assigning function result to variable. Even when I mapped the hits array to a new return value it came back undefined. i is also defined and likewise allowed to leak out. var in JavaScript allows this. let does not. In JavaScript, functions are objects. You can work with functions as if they were objects. For example, you can assign functions to variables, to array elements, and to other objects. They can also be passed around as arguments to other functions or be returned from those functions.

The result is undefined since $.ajax runs an asynchronous operation. Meaning that return status gets executed before the $.ajax operation finishes with the request.

You may use Promise to have a syntax which feels synchronous.

function doSomething() { 
    return new Promise((resolve, reject) => {
        $.ajax({
            url:'action.php',
            type: "POST",
            data: dataString,
            success: function (txtBack) { 
                if(txtBack==1) {
                    resolve(1);
                } else {
                    resolve(0);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                reject(textStatus);
            }
        });
    });
}

You can call the promise like this

doSomething.then(function (result) {
    console.log(result);
}).catch(function (error) {
    console.error(error);
});

or this

(async () => {
    try {
        let result = await doSomething();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
})();

Save returned value from a function to a variable, Save returned value from a function to a variable : Function « Language Basics « JavaScript DHTML. a value. 9. A Function Can Be Set Up to Accept a Variable Number of Arguments. 10. Using an Argument with a JavaScript Function. 13. Summary. A function is just a declaration until it is explicitly evaluated. The declaration can be assigned to a variable, which can then be passed as a parameter to another function. Thus, a JavaScript Function is a JavaScript Variable until it is executed (evaluated).

How to Return a Value in JavaScript, For example, with that function, you can set a variable to the value that is returned using the following code (which would set result to 5). var result  JavaScript Function Syntax. A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2,

Assign variable to function VS assign function to variable, So I assume in js we do not assign functions to variables, we assign the When a function has no return statements, their return values are  In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. A variable declared without a value will have the value undefined. The variable carName will have the value undefined after the execution of this statement:

JavaScript Functions, In JavaScript, if no return value is specified, the function will return undefined . we are setting the anonymous function object equal to a variable. If your function has no parameters, you can invoke it with an empty set of  Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.

Comments
  • Already got the correct wording in your title: return value. But you are not using return in your function ;)
  • Note that usually you don't need to initialize new variables with values if those values are falsy (which an empty string is). You can just write: var response; The value of response will be set to the undefined value in this case (which is also a falsy value). Then later, when you want to check if the value has been set, you can just check if it is falsy or not...
  • @Felix: i have a ajax call inside the function, it is returning "undefined". any idea? Thanks
  • Search here on SO about this issue. This is normal. You cannot return a value form an Ajax call, because it is executed asynchronously, i.e. the return statement is executed before the Ajax call finished. You can solve this using callbacks...
  • @Felix: Hi, i made a little change in the code, after success condition, i just include "async :false".... now the code is working fine as expected :)
  • For the curious, this is called an immediately invoked function express (IIFE). And it is awesome.
  • Note that the function itself is inside parenthesis (there is an opening parenthesis before the word function) and that there is an extra () at the end. (It was not obvious to me at first sight)
  • How do I pass parameters using this syntax?
  • @LeonardNiehaus (function(w) { /*…*/ })(window)
  • Its working... but i have ajax call inside, in thats time the result is 'undefined'. Any idea? Please look at the modified sample code.