0

I have a return from a javascript function that looks like this:

return{"success": true, "message": "Password changed."};

How do i retrieve these when calling this funciton?

1
  • 2
    It's returning an object. You use the normal syntax for accessing properties of an object. Commented Jan 31, 2015 at 11:30

4 Answers 4

2

You are returning an Object, You can save it in a variable and then can access the object properties.

//function definition
function fun1(){
return{"success": true, "message": "Password changed."};
}

//function calling
var res1 = fun1();

//using the result returned by function call
if(res1.success)//true
{
    alert(res1.message);//"Password changed.
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's just an object. Just access the properties.

var obj = foo();
for(var key in obj)
    console.log(key, " = ", obj[key]);

You can also use just obj.success and obj.message to return the subsequent value.

Comments

0

That's not "multiple returns"; that's returning an object with properties. So the calling code receives an object, and then uses its properties:

var a = theFunction();
console.log(a.success);
console.log(a.message);

Comments

0
function functionReturningObject(){
   return{"success": true, "message": "Password changed."};
}

//  use a temporary variable!!! this is a valid syntax but will execute twice
//     success = functionReturningObject().success
//     message = functionReturningObject().message
var map = functionReturningObject();

// when you know it contents you refer it directly
console.log(map.success)
console.log(map.message)

// when you do not know it contents, you can "explore" it
Object.keys(map).forEach(function(key){console.log(key);console.log(map[key]);})

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.