Function Selection

Due to the many similarities between scope functions, choosing the right one for your use case can be tricky. The choice mainly depends on your intent and the consistency of use in your project. Below, we provide detailed descriptions of the differences between scope functions and their conventions.

To help you choose the right scope function for your purpose, we provide this table that summarizes the key differences between them.

FunctionObject ReferenceReturn ValueIs extension function

letIt

it

Lambda Result

Yes

runIt

this

Lambda Result

Yes

runIt

-

Lambda Result

No: called without the context object

withIt

this

Lambda Result

No: takes the context object as an argument.

applyIt

this

Context Object

Yes

alsoIt

it

Context Object

Yes

Note that letIt and alsoIt can be called with standard lambda/arrow functions, but because JavaScript arrow functions don't have an own this context, runIt and applyIt have to be called with standard functions.

Detailed information about these functions is provided in the dedicated sections below.

Here is a short guide for choosing scope functions depending on the intended purpose:

  • Executing a lambda on non-nullable objects: letIt

  • Introducing an expression as a variable in local scope: letIt

  • Object configuration: applyIt

  • Object configuration and computing the result: runIt

  • Running statements where an expression is required: non-extension runIt

  • Additional effects: alsoIt

  • Grouping function calls on an object: withIt

The use cases of different scope functions overlap, so you can choose which functions to use based on the specific conventions used in your project or team.

Although scope functions can make your code more concise, avoid overusing them: it can make your code hard to read and lead to errors. We also recommend that you avoid nesting scope functions and be careful when chaining them because it's easy to get confused about the current context object and value of this or it.

Last updated