5

As title, I am getting the result that I wanted from console.log(result), however, how can I pass this console.log result to the string variable and "return" it? I am having trouble returning the result of console.log(). Thanks!

var type = ["men","women","boys", "girls"]
var product = "women shoes";
product.split(' ').forEach(function(item){
    type.forEach(function(elem){
      if(elem==item){
        console.log(elem);
      }
    });
});

Thank you for all the answers here, and it is so amazing that so many people are willing to help my beginner problem. Let me clear my question a little bit here, like above, console.log (elem) will return woman, however, if i replace the line concole.log(elem) with return(elem) will get me nothing. Why is that?

4
  • why don't you just return the result variable in your console.log() ? Commented Feb 16, 2017 at 16:49
  • 2
    I don't understand. console.log will just print whatever value you pass it to the console. That same value is still available. Could you please create a MCVE to show us your problem? Commented Feb 16, 2017 at 16:49
  • Do you want to convert result to a string? Then JSON.stringify is your friend: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Feb 16, 2017 at 16:51
  • As @PatrickHund said, if you are logging and array and you want to get the string of the array you should consider using JSON.stringify() but once again, this question lack a lot of information. Commented Feb 16, 2017 at 16:53

1 Answer 1

3

console.log formats whatever you pass inside to a string and outputs it. You can do the same, by explicitly calling toString() as follows:

console.log(result);

return result.toString();

As mentioned in the comments by @Patrick Hund, if result is a Javascript object, you can use JSON.stringify to convert it to a string (and then return it) as follows:

return JSON.stringify(result, null, 2);
Sign up to request clarification or add additional context in comments.

1 Comment

This is not completely correct. As described here: stackoverflow.com/questions/28397861/… the behaviour for Node.js may be different

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.