Sam
Sam

Reputation: 30396

Is return needed in JavaScript functions that do not return anything

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

Answers (3)

Samplasion
Samplasion

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

SasoN
SasoN

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

CertainPerformance
CertainPerformance

Reputation: 371233

No, in standard JavaScript, at the bottom of a function, if the return value isn't used;

  • return is equivalent to
  • return <someExpressionWithoutSideEffects>, which is equivalent to
  • nothing at all (no return statement at the end)

Note 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

Related Questions