FAQ: The State Hook - Lesson Review

It has to do with implicit/explicit returns. If the body of the function has more than one statement, then it is necessary to use curly braces. When the body of the function is just one expression, then we have a choice. The two choices are:

  • Choice A: We can enclose the expression in curly braces. But, if the function is meant to return some value, then we must do an explicit return by using the return keyword. If we omit the return keyword, then the function’s return will be undefined.

  • Choice B: We can choose to omit the curly braces. Whatever the expression evaluates to will be returned implicitly. Trying to return explicitly using the return keyword is not allowed and will cause error to be thrown.

Either we go with Choice A or with Choice B. What we aren’t allowed to do is mix the two approaches. If we go with Choice A (wrap in curly braces) and wish to return something, then we can’t omit the return keyword. If we go with Choice B (omit the curly braces), then we can’t do an explicit return by using the return keyword.

// Explicit Return 
const myFunc1 = (number) => {
    return number + 5;
}

// Implicit Return
const myFunc2 = (number) => number + 5;

// Curly Braces without explicit return will cause undefined return
const myFunc3 = (number) => {
    number + 5;
}

// No Curly Braces and explicit return will cause SyntaxError
const myFunc4 = (number) => return number + 5;

a = myFunc1(10);   // a will be 15
b = myFunc2(10);   // b will be 15
c = myFunc3(10);   // c will be undefined
d = myFunc4(10);   // SyntaxError

There is a twist though. Suppose we want to do an implicit return of an object. We may try to do something like:

/// Curly brace of object mistaken for curly brace of function body

const myFunc = () => { cars: 4, bikes: 7}

a = myFunc();  // SyntaxError

const myFunc = () => { cars: 4 }

a = myFunc();  // undefined

Since Javascript looks at the curly braces in this context as designating the body of a function, so we can’t just use curly braces. We have to wrap them in parentheses so that Javascript knows that this is meant to be an object and not the body of the arrow function. Have a look at this article. It is a short read, but it explains the issue very nicely with examples.

// Implicit Return of an object
const myFunc = () => ({cars: 4, bikes: 7})

a = myFunc();  // a will be {cars: 4, bikes: 7}

We can also do an explicit return, but we must use the return keyword if we want to return some value.

// Explicit Return of an object
const myFunc = () => { 
    return {cars: 4, bikes: 7};
}
a = myFunc();  // a will be { cars: 4, bikes: 7}

In the exercises you mentioned, we are using arrow functions in state setters. State setters expect that some value will be returned to them so that they can replace the previous state with the new state. As long as you respect the syntax of implicit/explicit returns, both approaches can be used.

2 Likes