Function tricks
Denys
Posted on May 30, 2024
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
}
}
This function just returns an object with sum and multiplied values.
We can invoke the function like:
test(1,2) // -> {sum: 3, multiplied: 2}
But also we can modify our function to:
function test(a,b){
this.sum = a + b
this.multiplied = a * b
}
In this case, we have no return statement, but in the return of invocation like this:
new test(1,2)
we will have the same structure, smth like this:
test {
sum: 3,
multiplied: 2,
__proto__: { constructor: Ζ test() }
}
Case #2
The typical way to invoke the function:
//....
testFunction(a,b,c)
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!"
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!"
Weird, but possible:
function test(){
return { message: "Hi there!" }
}
test.useTest = function(){
return this()
}
console.log(test.useTest()) // -> "Hi there!"
for example in React
we can use this approach for compositing our components.
Conclusion
JS is tricky and not as simple as it looks.
Posted on May 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.