Javascript Interview Question: Invoke a function without parenthesis
Exploring Unconventional JavaScript Calls: Mastering the Art of Invoking Functions Without Parentheses
A few years ago, I was posed with this question during an interview. Initially, I was perplexed — how could one call a function without using parentheses?
However, upon conducting further research, I discovered that the answer was surprisingly straightforward. Before delving into the various methods of calling a function, let’s explore the different ways it can be done.
First let’s see what are different ways we can call a function.
1. Direct Invocation
function show() {
console.log('show function');
}
show();
2. Using call and apply.
function show() {
console.log('show function');
}
show.call({});
show.apply({});
3. Using setTimeout
passing function as callback, but even in this we are using parenthesis
function show() {
console.log('show function');
}
setTimeout(show, 0);
4. using new keyword
function show() {
console.log('show function');
}
new show();
In all the 4 ways mentioned way we are using parenthesis.
But we have other ways to call a function which doesn’t uses parenthesis.
Solution 1
With new
we can invoke a function without parentheses. The parenthesis are only required when we want to pass some default values.
function show() {
console.log('show function');
}
new show; // logs show function
Solution 3
Using getter property in object
const obj = {
show: 1,
get show() {
console.log('show function');
}
}
obj.show;
Javascript is really awesome, let me know in comments if you found it interesting.
Read my other articles: