Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

91
Views
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?

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

7 months ago · Juan Pablo Isaza Report

0

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.

7 months ago · Juan Pablo Isaza Report

0

You don't have to return a value from a function. Note that functions do have a default return value which is undefined.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.