Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Space After Function [closed]

I know that white space is irrelevant in JavaScript, but I am curious about style.

When defining a function like:

function Foo(a, b, c) {}

I do not put a space after the function name. But, if I am creating a function as an expression:

Bar(function (a, b, c) {
    // do something
})

or

{
    Foo: function (a, b, c) {
        // do something
    }
}

I find myself naturally typing a space. I think this is because I've trained myself to type a space immediately after the function keyword (or keywords in general). However, depending on the context, space can look awkward. What makes more sense? what do most people do?

Sorry if this has been asked before; I didn't see it come up.

like image 492
Travis Parks Avatar asked Feb 15 '12 20:02

Travis Parks


2 Answers

I do the same.

function () { ... }
function name() { ... }

It makes more sense to me this way. It is more readable with the space after the function keyword (I do the same with if, while, etc) and it makes sense not to put it after the function name since you usually invoke it without a space.

like image 81
J. K. Avatar answered Oct 19 '22 00:10

J. K.


It is matter of personal preference. No doubt proper spacing does aid to readability which is always a good idea.

The important thing though when it comes to JavaScript coding style, is to always put starting curly brace on the same (due to automatic semi-colon insertion) line unlike:

function myFunc() 
{
    return
    {
        name: 'Jane'
    };
}

var f = myFunc();
console.log(f); // undefined

Read More:

  • Code Conventions for the JavaScript Programming Language
like image 5
Sarfraz Avatar answered Oct 18 '22 23:10

Sarfraz