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
  }
}
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

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

We can invoke the function like:

test(1,2) // -> {sum: 3, multiplied: 2}
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

But also we can modify our function to:

function test(a,b){
  this.sum = a + b
  this.multiplied = a * b
}
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

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

new test(1,2)
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

we will have the same structure, smth like this:

test {
  sum: 3,
  multiplied: 2,
  __proto__: { constructor: ƒ test() }
}
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

Case #2

The typical way to invoke the function:

//....
testFunction(a,b,c)
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

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!"
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

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!"
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

Weird, but possible:

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

console.log(test.useTest()) // -> "Hi there!"
🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025 🔥 ข่าวด่วน: lgtome/function tricks aa - Kapook Update 2025

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)