Javascript – almost not line based

Javascript is not a line based language. White space has the same meaning regardless if it’s a space, a tabulator character or a line break. Well, almost.

You can format the code pretty much any way you like.  If you have a function like this:

function getAnswer() {
   var answer = 42;
   return answer;
}

You can format it like this:

function getAnswer() { var answer = 42; return answer; }

Or like this:

function
getAnswer
()
{
var answer
=
42;
return answer
;
}

However, there are a few things that you can’t do. If you for example put a line break between the return keyword and it’s argument, it suddenly has a different meaning. If you format the code like this:

function getAnswer() {
   var answer = 42;
   return
      answer;
}

Then it is interpreted like this:

function getAnswer() {
   var answer = 42;
   return;
   answer;
}

The return statement takes it’s parameterless form, and the argument becomes a statement of it’s own.

This is usually not a problem, especially if you format the code in a sensible way, but someday it can come and bite you…

Author: Göran Andersson

Comments are closed.