r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

Show parent comments

-2

u/[deleted] Nov 10 '20

Even with the explanation and this example, I just don't understand.

I know if there is a callback or not. I use the function because I know what the function does, the parameter syntax, including whether or not it has a callback, and what the callback does. When do you not know if there is a callback to a function? Isn't that what reading the documentation is for?

9

u/N074R0807 Nov 10 '20

Following this specific example, you can have a function that accepts an optional callback function as an argument. The term optional is key here. In that function's implementation you have to check whether a callback function was supplied or not, so you can either invoke it or skip it.

Example:

// definition/implementation
function updateUserStats(userInfo, callback) {
	// do something with userInfo
	// after doing that, the code will check is there's a callback to invoke
	if (typeof callback === 'function') {
		callback();
	}
}

// now, using it in two different ways

// without using the optional callback
const user1 = {
	name: 'John',
	age: 32
}

updateUserStats(user1);

// using the optional callback
const user2 = {
	name: 'Jill',
	age: 35
}

function notifyUserUpdated() {
	alert('User stats was updated successfully')
}

updateUserStats(user2, notifyUserUpdated);

1

u/[deleted] Nov 10 '20

That makes more sense. Thank you.

1

u/N074R0807 Nov 10 '20

No problem! I guess what confused you is the fact that you were thinking in terms of using a pre-existing function not implementing your own.