Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible to return a value from Javascript function parameter?

Tags:

javascript

I'd like my function to return both an error code and a string value, so plan to use return to return the error code and use a parameter to return the string value. But it doesn't work. Looks like we can't return a value from function parameter. Any idea how to return it from function parameter?

Below is a sample code. I hope to get the retVal from sayHello's parameter.

function sayHello(name, retVal) {
    retVal = "hello " + name;
    return 1;
}
like image 726
zhongzhu Avatar asked Dec 11 '22 13:12

zhongzhu


1 Answers

You can probably do this way, pass an object back.

function sayHello(name) {

    retVal = "hello " + name;
    return {code: 1, message: retVal};
}

//And while calling
var returnVal= sayHello("something");
var code = returnVal.code;
var msg= returnVal.message;

Reason why retVal is nt available outside is because of variable hoisting in the scope inside the function. But you can also work around that by not passing it in as argument.

var retVal; //Define it in an outer scope.
function sayHello(name) {
    retVal = "hello " + name;
    return 1;
}
var returnVal= sayHello("something");
alert(returnVal);
alert(retVal); //Now get it here.
like image 196
PSL Avatar answered Feb 19 '23 01:02

PSL