Invoking a function without parentheses

Viewed 92254

I was told today that it's possible to invoke a function without parentheses. The only ways I could think of was using functions like apply or call.

f.apply(this);
f.call(this);

But these require parentheses on apply and call leaving us at square one. I also considered the idea of passing the function to some sort of event handler such as setTimeout:

setTimeout(f, 500);

But then the question becomes "how do you invoke setTimeout without parentheses?"

So what's the solution to this riddle? How can you invoke a function in Javascript without using parentheses?

8 Answers

In ES6, you have what's called Tagged Template Literals.

For example:

function foo(val) {
    console.log(val);
}

foo`Tagged Template Literals`;

Here is another example where I am passing function one in then function without parantheses and it is called.

function one() {
  console.log("one called");
}
function two() {
  return new Promise((resolve, reject) => {
    resolve();
  });
}
two().then(one);

You can use an anonymous function. It only works using pre-ES6 syntax, but still, it works.

Code:

//ES6+ (using const, still not using arrow functions)
const myFunc = (function(args){console.log("no parenthesis")})(args);

and invoke it like this:

myFunc;
// ^^^ no parenthesis in invocation, but you do have parenthesis in definition
// also note that the semicolon is optional if it is the only thing on the line

Before ES6:

var myNonES6Func = (function(args){console.log("Use var before ES6.")})(args);

and invoke it like this

myNonES6Func;
// ^^^ same as the ES6 invocation.

const es6_func = (function() {
    alert("ES6!")
})();
var before_es6_func = (function() {
    alert("Before ES6.")
})();
const es6 = () => {
    es6_func
}

function before_es6() {
    before_es6_func
}
<button onclick="es6">ES6+</button>
<button onclick="before_es6">Before ES6</button>

NOTE: Modern browsers do not seem to have this functionality anymore (it calls itself on page load, but when you called it normally, it would also work but you would have to add some counting code to keep it from running on page load) I did test it on Internet Explorer 11, and it seems to still work though, but Chrome, Firefox, and Edge do not work, it might've just been a bug in IE.

Related