Returning

Returning is a shift of control from a function to its caller. It is achieved either via an explicit return statement within the function itself or implicitly when the function runs to completion:

function sayHiToMe(name) {

if (name) {
return `Hi ${name}`;
}

// In the case of a truthy `name` this code is never arrived at
// because `return` exists on a previous line:
throw 'You do not have a name! :(';

}

sayHiToMe('James'); // => "Hi James"

Here, you'll notice that we don't bother placing the implied else condition of a falsy name in its own else block (else {...}) as this would be unnecessary. Because we return when the name is truthy, any code following that return statement will therefore only run in the implied else condition. It's quite common to see such patterns in functions that carry out preemptive input checks:

function findHighestMountain(mountains) {

if (!mountains || !mountains.length) {
return null;
}

if (mountains.length === 1) {
return mountains[0];
}

// Do the actual work of finding the
// highest mountain here...
}

As we see here, returning is not only used to return control to the caller but also for its side-effect: avoiding work that exists on lines below itself in its function. This is often termed returning early and can significantly help to reduce the overall complexity of a function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.84.112