Hello guys,
I am having a confusion regarding when “return” can and cannot be omitted in method definition especially in class.
Theoretically, all functions including Arrow functions need “return” if it comes with curly braces but I have noticed that in many method definitions it does not provide “return” and it still works.
For example, “greetParent” below for a React application can be written in 4 different ways with/without “return” and all of them worked :
function ChildComponent(props) {
return (
<div>
<button onClick={() => props.greetHandler('child')}>Greet Parent</button>
</div>
)
}
class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
parentName: 'Parent'
}
this.greetParent = this.greetParent.bind(this)
}
// Traditional function with return
greetParent(childName) {
return alert(`Hello ${this.state.parentName} from ${childName}`)
}
// Arrow function with return
greetParent = childName => {
return alert(`Hello ${this.state.parentName} from ${childName}`)
}
// I do not quite understand why "return" can be omitted here?
greetParent(childName) {
alert(`Hello ${this.state.parentName} from ${childName}`)
}
// Again, I do not quite understand why "return" can be omitted for Arrow syntax here?
greetParent = childName => {
alert(`Hello ${this.state.parentName} from ${childName}`)
}
render() {
return (
<div>
<ChildComponent greetHandler={this.greetParent}/>
</div>
)
}
}
And particularly for Arrow function, it requires “return” when curly braces are present:
let add100 = (a) => {
a + 100;
}
console.log(add100(7)) // undefined
let add100 = (a) => {
return a + 100;
}
console.log(add100(7)) // 107
Any idea please?
Thank you in advance.