Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I omit Return value in arrow function in JavaScript?

I've been struggled from this for a long time. we all know that arrow function simplifies the syntax, like this:

A. Arrow function:

        onClick={() => toggleTodo(todo.id)}

B. Expand the Arrow function:

        onClick={() => {
           // we can see there is a return keyword here. can I just remove the return keyword ? 
           return toggleTodo(todo.id); 
           ^^^^^^
        }}

In the official redux tutorial, the file AddTodo.js:

import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'

const AddTodo = ({ dispatch }) => {
  let input

  return (
    <div>
      <form
        onSubmit={e => {                   // focus on this line
          e.preventDefault()
          dispatch(addTodo(input.value)).  // focus on this line, if i put return here, the code below won't be executed. if not, how to explain the syntax in the beginning?
          input.value = ''
        }}
      >
        <input ref={node => (input = node)} />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  )
}

export default connect()(AddTodo)

The question is: in the onSubmit, why we don't need to put a return inside the function body ? Thank you.

like image 877
Reacher Avatar asked Feb 19 '26 18:02

Reacher


1 Answers

You only need to return something if that returned value will be used somewhere. In the case of onSubmit, there is no need to return anything. That (arrow) function is simply running some code when the form is submitted.

In point B in your question, yes, you can remove return if nothing needs to be done with the returned result of toggleTodo(todo.id).

like image 105
Matt U Avatar answered Feb 22 '26 07:02

Matt U



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!