Returning values

An arrow function may have a block of code with some return statements in it or it may just be an expression. The former case is most similar to the standard way of defining a function; for example, we could write a function to add three numbers as follows, using both styles. We should add data types to the definitions, but we'll get to that soon:

function addThree1 (x, y, z) {
const s = x + y + z;
return s;
}

const addThree2 = (x, y, z) => {
const s = x + y + z;
return s;
};

If you can do this just by returning an expression, you can then write an equivalent version; just write whatever you want to return immediately after the arrow:

const addThree3 = (x, y, z) => x + y + z;

There's a special case: if you are returning an object, then you must place it within parentheses because otherwise JS will confuse it with a block of code. For Redux (which we'll be seeing in the Managing State with Redux section of Chapter 8, Expanding Your Application), you might want to write an action creator that returns an action, namely an object with a type attribute and possibly some more:

const simpleAction = (t, d) => {
type: t;
data: d;
};

console.log(simpleAction("ADD_KEY", 229)); // undefined

What's happening here? JS is interpreting the braces as a block, and then type and data are considered to be labels (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label if you don't remember these!), so the whole object is really a block that just doesn't return anything, and JS returns an undefined result. Just placing the object in parentheses will work as expected:

const simpleAction = (t, d) => ({
type: t;
data: d;
});

// this works as expected
..................Content has been hidden....................

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