Syntax Design – Why Use Parentheses When No Arguments are Passed?

language-designprogramming-languagessyntax

In many languages, the syntax function_name(arg1, arg2, ...) is used to call a function. When we want to call the function without any arguments, we must do function_name().

I find it strange that a compiler or interpreter would require () in order to actually detect it as a function call. If something is known to be callable, why wouldn't function_name; be enough?

On the other hand, in some languages we can do: function_name 'test'; or even function_name 'first' 'second'; to call a function or a command.

I think parentheses would have been better if they were only needed to declare the order of priority, and in other places were optional. For example, doing if expression == true function_name; should be as valid as if (expression == true) function_name();.

An especially interesting case is writing 'SOME_STRING'.toLowerCase() when clearly no arguments are needed by the prototype function. Why did the designers decide against the simpler 'SOME_STRING'.lower design?

Disclaimer: Don't get me wrong, I quite love the C-like syntaxes! I'm just asking for the reasoning behind it. Does requiring () have any actual advantages, or does it simply make the code more human readable?

Best Answer

For languages that use first-class functions, its quite common that the syntax of referring to a function is:

a = object.functionName

while the act of calling that function is:

b = object.functionName()

a in the above example would be reference to the above function (and you could call it by doing a()), while b would contain the return value of the function.

While some languages can do function calls without parenthesis, it can get confusing whether they are calling the function, or simply referring to the function.

Related Topic