Reputation: 30396
In JavaScript, I understand that return
will both return some output a function may produce and stop the execution of that function.
My question is about those cases where the function doesn't return anything. It only performs something.
I primarily use JavaScript within the context of React and React Native so my examples are in React Native.
First example is a function that simply removes something from AsyncStorage
. I typically use this when a user signs off. Do I need return
in this case?
export const removeAuthData = async () => {
return await AsyncStorage.removeItem('auth');
}
Another example is when I have a function that may update the state in my app:
setIsAuthenticated(value) {
this.props.actions.setIsAuthenticated(value);
}
In these scenarios, do I need to use return
in my functions?
Upvotes: 0
Views: 110
Reputation: 537
Since JavaScript is a weakly typed language, the return type and value of the function are entirely dependent on the value of the return
.
Of course, if you don't plan on using the returned values of the functions, it doesn't matter whether you return
it or not. Still, it may be a stylistic choice to return
the last statement or not.
Lastly, if you return
the result of an expression with value undefined
, then it's completely indistinguishable, without looking at the body of the function, whether you actually returned or not.
TL;DR: Not needed, but up to stylistic choice and preference.
Upvotes: 1
Reputation: 150
You don't have to return a value from a function.
Note that functions do have a default return value which is undefined
.
Upvotes: 0
Reputation: 371233
No, in standard JavaScript, at the bottom of a function, if the return value isn't used;
return
is equivalent toreturn <someExpressionWithoutSideEffects>
, which is equivalent toNote that for those using TypeScript, things are a bit different - using the return
keyword indicates that you really are trying to transfer a value from the function to its caller, in which case return
or return undefined
is not quite the same as lacking a return
statement at all.
Upvotes: 1