concept return statement in category angular

appears as: return statement
Getting MEAN with Mongo, Express, Angular, and Node.js 2ED

This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.

To respond with error messages, the controller needs to be set up to trap potential errors and send an appropriate response. Error trapping in this fashion typically involves if statements. Every if statement must have a corresponding else statement or include a return statement.

Taking declarations out of the return statement

Providing a return in the aforementioned way is also a stylistic convention but is again one that helps you and others understand your code when you come back to it after a break. When you use this approach, the return statement contains a list of the functions that you’re returning without any of the actual code. The code is declared in functions above the return statement, although within the same module. The following code listing shows an example.

Listing D.55. Revealing module pattern, short example
const userAge = (function () {
  let myAge;
  const setAge = function (initAge) {  #1
    myAge = initAge;                   #1
  };                                   #1
  return {
    setAge                             #2
  };
})();

You can’t see the benefit of this approach in such a small example. We’ll look at a longer example soon that will get you part of the way there, but you’ll see the benefits when you have a module that runs to several hundred lines of code. As gathering all the variables at the top of the scope makes it obvious which variables are being used, taking the code out of the return statement makes it obvious at a glance which functions are being exposed. If you had a dozen or so functions being returned, each with a dozen or more lines of code, chances are that you wouldn’t to be able to see the entire return statement on one screen of code without scrolling.

What’s important in the return statement, and what you’ll be looking for, is which methods are being exposed. In the context of the return statement, you aren’t interested in the inner workings of each method. Separating your code like this makes sense and sets you up to have great, maintainable, and understandable code.