Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript when function parentheses are not optional


May 09, 2021 CoffeeScript


Table of contents


When function parentheses are not optional

Problem

You want to call a function without arguments, but you don't want to use parentheses.

Solution

Use parentheses anyway.

Another approach is to use the do notation, as follows:

notify = -> alert "Hello, user!"
do notify if condition

Compiled into JavaScript can be expressed as:

var notify;
notify = function() {
    return alert("Hello, user!");
};
if (condition) {
    notify();
}

Discuss

This method is similar to Ruby in that it can be called without parentheses. T he difference is that CoffeeScript uses an empty function name as a pointer to a function. Since then, if you don't give a method any parameters, Then CoffeeScript won't be able to tell whether you want to call a function or use it as a reference.

Is this good or bad? I t's just different. It creates an unexpected example of syntax -- parentheses aren't always optional -- but it allows you to use names fluently to pass and receive functions, which is difficult for Ruby to implement.

For CoffeeScript, using do notation is an ingenious way to overcome parenthesis. Although some people prefer to write out all the parentheses in a function call.