r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

15

u/wobsoriano Nov 10 '20 edited Nov 10 '20

Some use case

A function as a prop in a React component

export default function App ({ user, sampleFunction }) {
	const anotherFunction = () => {
		// logic
		sampleFunction?.();
	}

	return <div>Hello { user }!</div>
}

A callback function

function RandomFunction(arg1, arg2, callback) {
	// logic
	callback?.()
}

Edit:

Yes, an if statement would be better and readable but if you check my post, it's not an if statement I'm comparing it to.

myFunction && myFunction();

-13

u/OmgImAlexis Nov 10 '20

An if statement would be a lot easier to read. I don’t see any reason to use this.

Just because you can do it doesn’t mean you should.

7

u/wobsoriano Nov 10 '20

If you look at the screenshot example, there is no if statement. I'm comparing it with

myFunction && myFunction();

-16

u/OmgImAlexis Nov 10 '20

You don’t say...

I’m saying an if would have been better. Even the example you’re comparing it to isn’t the best.

5

u/wobsoriano Nov 10 '20

Sure thing. That is noted sir.

-15

u/OmgImAlexis Nov 10 '20

Not a guy.

3

u/wobsoriano Nov 10 '20

*ma'am.

-19

u/OmgImAlexis Nov 10 '20

No need for either and I never said I’m a women or use ma’am. It’s 2020 learn.

8

u/wobsoriano Nov 10 '20

Okay. Point taken 😃