🍻Scope Functions

The Katxupa library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object through it or in some cases this. Such functions are called scope functions.

There are five of them: letIt, runIt, withIt, applyIt, and alsoIt.

Basically, these functions all perform the same action: execute a block of code on an object. What's different is how this object becomes available inside the block and what the result of the whole expression is.

Here's a typical example of how to use a scope function:

({name: "Manuel Santos", age: 36, email: "ney.br.santos@gmail.com"})
    .letIt(it => {
        console.log(it);
        it.age++;
        console.log(it);
    });

If you write the same without letIt, you'll have to introduce a new variable and repeat its name whenever you use it.

const user = {name: "Manuel", age: 36};
console.log(user);
user.age++;
console.log(user);

Scope functions don't introduce any new technical capabilities, but they can make your code more concise and readable.

Last updated