DEV Community

Denys
Denys

Posted on

Function tricks

Motivation

Some JS features are hidden under the hood or veiled under some expressions, etc.

This article is about to enlighten some features or approaches that are not on the surface.

Prerequisites

JS knowledge and that's all.

Case #1

We have a simple code:

function test(a,b){
  return {
    sum: a + b,
    multiplied: a * b
  }
}
Enter fullscreen mode Exit fullscreen mode

This function just returns an object with sum and multiplied values.

We can invoke the function like:

test(1,2) // -> {sum: 3, multiplied: 2}
Enter fullscreen mode Exit fullscreen mode

But also we can modify our function to:

function test(a,b){
  this.sum = a + b
  this.multiplied = a * b
}
Enter fullscreen mode Exit fullscreen mode

In this case, we have no return statement, but in the return of invocation like this:

new test(1,2)
Enter fullscreen mode Exit fullscreen mode

we will have the same structure, smth like this:

test {
  sum: 3,
  multiplied: 2,
  __proto__: { constructor: ƒ test() }
}
Enter fullscreen mode Exit fullscreen mode

Case #2

The typical way to invoke the function:

//....
testFunction(a,b,c)
Enter fullscreen mode Exit fullscreen mode

but we have another method to invoke if we have no args(e.g):

function test(){
  return { message: "Hi there!" }
}

const data = new test

console.log(data.message) // -> "Hi there!"
Enter fullscreen mode Exit fullscreen mode

Case #3

The regular way that we can use it provides the object on the return statement inside the function, but we can use it outside if we need it.

Regular:

function test(){
  return { message: "Hi there!" }
}

console.log(test()) // -> "Hi there!"
Enter fullscreen mode Exit fullscreen mode

Weird, but possible:

function test(){
  return { message: "Hi there!" }
}
test.useTest = function(){
  return this()
}

console.log(test.useTest()) // -> "Hi there!"
Enter fullscreen mode Exit fullscreen mode

for example in React we can use this approach for compositing our components.

Conclusion

JS is tricky and not as simple as it looks.

Top comments (0)