Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the most convinient way to return second value from a function
    text
    copied!<p>Working with JavaScript from time to time, I try to use a pattern I was getting used to with another language. It's when the function result is about success of the operation and one of the parameters is the reference to the actual returned value. </p> <p>Knowing that there's no passing by reference in JavaScript, the only way is to use objects (including arrays). So something like</p> <pre><code>function getSomething(res) { if (....) { res["value"] = 123; return true; } else return false; } </code></pre> <p>But this leads to several inconveniences. One of them is when I actually use this function, I should not forget about the convention so my natural way to deal with this is </p> <pre><code> var value = {}; if (getSomething(value)) { if (value == 123) { } } </code></pre> <p>when the right way which I should remember is </p> <pre><code>... if (value["value"] == 123) ... </code></pre> <p>Also if I forget to initialize value with {} then I get another error. </p> <p>So, maybe it's a question for those who mix languages. What is a convention you consider convenient for such return pattern?</p> <p><strong>UPDATE</strong>: As an example of an actual code fragment that would appear in a C program </p> <pre><code>if (getSomethingA(&amp;res1) &amp;&amp; getSomethingB(&amp;res2) &amp;&amp; getSomethingC(&amp;res3)) { ... v = res1*res2*res3; ... } </code></pre> <p>I can not figure out how can I implement something like this in JavaScript without "not so easy to always remember conventions" or too many lines. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload