I rarely use return in JavaScript and only use it whenever I want the function to behave exactly what I want it do or return an unmistakable value. Recently, I've read people conversation that return can help improve performance if do it properly like it would put brake on the function when criteria matched. So the function stopped and you don't waste the resources to process it. I do not understand how this might work. I mean how something like this would work: function example() { var abc; // do something with abc return xyx; // if xyz is undefined so do something else } Code (markup): Can anyone give me working example? How would this compare to if else statement? Hope that was clear.
You have two options put the looping code into a function and return when you have your value or keep the loop in the main code and break to stop processing. <script type='text/javascript'> function example(str){ var choices = <?php echo json_encode($customerlist); ?>; for (var i = 0; i < choices.length; i++) { if (choices[i].name == str) return choices[i].id; } return false; } var id = example('sarahk'); // you can now test if id has a value and continue processing Code (markup): or you could do this <script type='text/javascript'> var choices = <?php echo json_encode($customerlist); ?>; var id=false; for (var i = 0; i < choices.length; i++) { if (choices[i].name == str) id = choices[i].id; break; } } // you can now test if id has a value and continue processing Code (markup): FWIW I'd go for the function everytime
Hi @Achiever, I don't really want a working function. I just need example, a guide to give me direction. I can develop any JavaScript functionality for my need. That would help me an idea where to begin with. Thanks,
Finally, someone has written a tutorial: http://krasimirtsonev.com/blog/article/return-statement-is-not-the-end-but-it-should-be Not complete though,