Javascript Code Styling

T

Tom Cole

I'm starting to do more quantity of javascript coding and thought this
might be a good time to investigate code styling. I primarily develop
in Java and currently use the code styling techniques spelled out for
Java.

For example, in my code blocks ( {} ) I always place the starting brace
on the same line as the first line of code. For example:

function myFunction {

But I've also noticed a lot of developers move it to the next line:

function myFunction
{

I also place a semicolon at the end of each line, although I see it's
also not mandatory.

Third (and lastly) I also declare all Objects in first letter uppercase
and all member variables/functions in lowercase. For example:

function MyObject() {

var myFirstMemberVar;

function doSomething() {
....
}
}

Is there a coding standard for Javascript? Do my current practices seem
feasible?

Thanks in advance.
 
L

Laurent Bugnion

Hi,

Tom said:
I'm starting to do more quantity of javascript coding and thought this
might be a good time to investigate code styling. I primarily develop
in Java and currently use the code styling techniques spelled out for
Java.

A few years ago, when we (I work at Siemens) started working on our
current wep application, we decided to write our own JavaScript coding
guidelines. Mostly, they are inspired of our C/C++ coding guidelines and
also of Java guidelines (because code found online mostly follows the
Java guidelines for capitalization for example).

For example, in my code blocks ( {} ) I always place the starting brace
on the same line as the first line of code. For example:

function myFunction {

But I've also noticed a lot of developers move it to the next line:

function myFunction
{

This is mostly a matter of taste. Our guidelines allow both but
recommend the second one, which we find is more readable. If you work
with Visual Studio 2003/2005, it's easy to configure

I also place a semicolon at the end of each line, although I see it's
also not mandatory.

Not mandatory in JavaScript, but it's very recommended. We made it
mandatory in our guidelines. If you use a code minimizer like JsMin,
placing more than one statement on one single line, then the ';' is
mandatory anyway.

Third (and lastly) I also declare all Objects in first letter uppercase
and all member variables/functions in lowercase. For example:

function MyObject() {

var myFirstMemberVar;

function doSomething() {
....
}
}

This is also what we recommend. However, we also recommend hungarian
notation for variables. This goes against our C# guidelines, but has a
reason: In JavaScript, objects are not strongly typed. Thus they may
contain a type first, and then another type. However, to avoid
confusion, our guidelines specify that this must be avoided, and a
variable must carry a single type all along its life. To facilitate
this, hungarian notation is used, for example strMessage (string),
iValue (integer numbers), fValue (float numbers), etc... Note that
JavaScript doesn't differentiate integer and float, so it's really just
to help the developer.

Generally, JavaScript coders follow the Java naming guidelines, like you.

Is there a coding standard for Javascript? Do my current practices seem
feasible?

Thanks in advance.

Yes, they seem very reasonable.

HTH,
Laurent
 
R

Richard Cornford

Laurent Bugnion wrote:
This is mostly a matter of taste. Our guidelines allow both
but recommend the second one, which we find is more readable.
<snip>

I have a feeling that the one of the two that is found more readable by
individuals is the one with which they are more familiar. I find the
former more readable. But I suspect that the most important thing is to
be consistent and use only one or the other (certainly within any single
project, and probably within any single company).
Generally, JavaScript coders follow the Java naming
guidelines, like you.

I certainly do.
Yes, they seem very reasonable.

Absolutely.

Richard.
 
K

Kevin Darling

Laurent said:
Hi,



This is mostly a matter of taste. Our guidelines allow both but
recommend the second one, which we find is more readable.

We do a lot of JS, and we prefer using the next line also. The old way
of using the same line is no doubt related to early terminal / memory
problems.
[...] hungarian notation is used, for example strMessage (string),
iValue (integer numbers), fValue (float numbers), etc... Note that
JavaScript doesn't differentiate integer and float, so it's really just
to help the developer.

We use these, plus oReference for objects.

Cheers , Kev
 
L

Laurent Bugnion

Hi Richard,

Richard said:
<snip>

I have a feeling that the one of the two that is found more readable by
individuals is the one with which they are more familiar. I find the
former more readable. But I suspect that the most important thing is to
be consistent and use only one or the other (certainly within any single
project, and probably within any single company).

Yes. We talked for a while about it, and decided to let the programmers
decide (for the record, the development lasted 2.5 years, involved about
30000 lines of JavaScript code, and we had 6 developers writing
JavaScript. Most of them had zero experience with the language, but are
very good C/C++/C# programmers. After a few internal courses, they were
totally up to the task). Mostly in my firm, the second form (bracket on
a different line) is used. This is probably why we found it more
readable. But as I said, it's very much personal.

Greetings,
Laurent
 
L

Laurent Bugnion

Hi,

Kevin said:
Laurent said:
[...] hungarian notation is used, for example strMessage (string),
iValue (integer numbers), fValue (float numbers), etc... Note that
JavaScript doesn't differentiate integer and float, so it's really just
to help the developer.


We use these, plus oReference for objects.

Cheers , Kev

Yes. We actually have more than these. For example, we also use "n" for
nodes (objects returned by document.getElementById). We made a list of
prefixes and strongly encourage the developers to use it. It's no
problem for them, as they were using hungarian notation in C++. It's
rather a problem that they have to abandon it in C# (we follow
Microsoft's recommendation for C#, for many reasons, including sharing
code with other Siemens divisions).

Greetings,
Laurent
 
S

scriptguru

Tom Cole напиÑав:
For example, in my code blocks ( {} ) I always place the starting brace
on the same line as the first line of code. For example:

function myFunction {

But I've also noticed a lot of developers move it to the next line:

function myFunction
{

Few days ago I found JS Editor and Code Chameleon developed by C-Point.
That tools can reformat any source and may be very useful sometimes. It
can be used as a reformatter ot beautifier.
I also place a semicolon at the end of each line, although I see it's
also not mandatory.

The semicolons may became a subject of one more Holy War :)
All programmers who used C/C++ before JS always use semicolons. I never
used C/C++ (we learned Pascal in school and college) and use semicolons
rarely. I think it is a benefit of language - free usage of semicolons.
And if some code minifier kills your code because of missing semicolons
then it is bad code minifier. Good code minifier never acts like this.
 
R

Richard Cornford

Tom Cole напиÑав:

The semicolons may became a subject of one more Holy War :)
All programmers who used C/C++ before JS always use semicolons.

This would probably be true of anyone coming form any language that
required semicolons to terminate lines. Overall Java probably has the
biggest influence on code styling in javascript (though maybe that is
not such a good idea).
I never used C/C++ (we learned Pascal in school and college) and use
semicolons rarely. I think it is a benefit of language - free usage of
semicolons.

Javascript doesn't really have free use of semicolons. Intact they are
not even optional, they just may be inserted automatically so do not
need to be in the source code. the problem with that is that you need
to appreciate when they will be inserted when writing anything but the
most 'normal' code. For example, two consecutive instances of the
inline execution of a function expression:-

(function(){
...
})();
(function(){
...
})();

- Omit the semicolons to give:-

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

- and the second parenthesised function expression becomes an argument
to a call to the return value from the call to the first function
expression, and the final set of parenthesise then become a call the
return value from that call. That is, something along the lines of:-

(((function(){;})())(function(){;}))();

- (which is completely legal and valid javascript)

The error is likely to be along the lines of "function expected" on the
line at the start of the second function expression, not easy to work
out what happened.
And if some code minifier kills your code because of missing
semicolons then it is bad code minifier. Good code minifier
never acts like this.

Which is not a reasonable comment on JsMin as JsMin requires that its
input first passes JsLint, and JsLint insists upon
statement-terminating semicolons as one of its 'best practice' criteria
for source code.

Richard.
 
D

Douglas Crockford

Tom said:
For example, in my code blocks ( {} ) I always place the starting brace
on the same line as the first line of code. For example:

function myFunction {

But I've also noticed a lot of developers move it to the next line:

function myFunction
{

I prefer the first form because it works better when a function literal is used
inline as an expression, particularly when passing a function as a parameter. In
that circumstance (which I use a lot), the second form reads badly.
I also place a semicolon at the end of each line, although I see it's
also not mandatory.

It is wise to include the semicolons. Semicolon insertion was intended to make
JavaScript more reliable, but dependence on it makes programs less reliable.
Third (and lastly) I also declare all Objects in first letter uppercase
and all member variables/functions in lowercase. For example:

function MyObject() {

var myFirstMemberVar;

function doSomething() {
....
}
}

What you are calling an Object there is usually called a Constructor. It is very
good practice to capitalize the names of constructors. The reason is that
calling a constructor without the new prefix can cause clobbering of the global
object, which is very bad. There is no compile-time or run-time notification of
this error. The only defense we have is a coding convention that we should use a
new prefix when invoking a capitalized function. (The exceptions are when
invoking String, Number, and Boolean which should never be called with the new
prefix.)
Is there a coding standard for Javascript? Do my current practices seem
feasible?

This is what I use: http://javascript.crockford.com/code.html
 
S

scriptguru

Richard Cornford напиÑав:
Javascript doesn't really have free use of semicolons. Intact they are
not even optional, they just may be inserted automatically so do not
need to be in the source code. the problem with that is that you need
to appreciate when they will be inserted when writing anything but the
most 'normal' code.

Yes, I know that JS parser/interpreter automaticaly inserts semicolons.
Thats why I love it :)
I am javascript/actionscript developer with ~6 years of experience. My
applications sometimes became really complicated (and I trying to use
full potential of JS). But no even one "Missing semicolon" errors or
any other problem with semicolons for last years.
Which is not a reasonable comment on JsMin as JsMin requires that its
input first passes JsLint, and JsLint insists upon
statement-terminating semicolons as one of its 'best practice' criteria
for source code.
I never said that JsMin or JsLint are bad or even not good enough. But
I saw many code minifiers that will destroy code if semicolons are not
used.

Val Polyakh
trickyscripter.com
 
J

Jim Ley

We do a lot of JS, and we prefer using the next line also. The old way
of using the same line is no doubt related to early terminal / memory
problems.

no, it's because it's the only correct way!

oops no, it's all about personal taste and consistency - I don't like
different line though as in my experience people too often make
mistakes in javascript

if (chicken==1)
{
alert(1)
}

too often for comfort get's changed too

if (chicken==1)
Egg()
{
alert(1)
}

which is a bug often not caught early, as it's purely a logic bug -
it's also easier to see the missing semi-colons - and these should be
mandatory in a coding style for other similar reasons.

Otherwise the only thing I would suggest is a set of rules that can be
done automatically by astyle - otherwise the developers you get who
are particularly uncomfortable in your style or you import a load of
code from a 3rd party makes changing it a boring manual process.
[...] hungarian notation is used, for example strMessage (string),
iValue (integer numbers), fValue (float numbers), etc... Note that
JavaScript doesn't differentiate integer and float, so it's really just
to help the developer.

We use these, plus oReference for objects.

These I find awful, it removes all link between the name of the
variable and its function - the type is less important than the
function. This difference tends to be common in visual and aural
people - those who sound out words struggle with hungarian, those with
visual minds find them better...

Jim.
 
L

Laurent Bugnion

Hi Jim,

Jim said:
These I find awful, it removes all link between the name of the
variable and its function - the type is less important than the
function. This difference tends to be common in visual and aural
people - those who sound out words struggle with hungarian, those with
visual minds find them better...

Jim.

I agree about the visual mind, I know I have one and when I program I
see the words in my mind and the objects they contain. It leads to an
interesting kind of "trance" sometimes.

That said, hungarian notation has another advantage for me (less in
JavaScript, but especially true in C#): I use Visual Studio 2005 to
program, and Intellisense is a huge help. When you use hungarian
notation, you don't need to remember the names of the variables, just
need to know their type, then type "str" and already you get a list of
all strings available in the scope. I find this a huge productivity
gain. But then again, maybe it's just the way I think.

Greetings,
Laurent
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Thu, 28 Sep 2006 13:59:30 remote, seen in
news:comp.lang.javascript said:
For example, in my code blocks ( {} ) I always place the starting brace
on the same line as the first line of code. For example:

function myFunction {

function myFunction() {

Always? If the block is conditional as
if (a && A && b ... && z && Z) { ... }
then you cannot put it on the first line unless that first line is made
too long. But you can put it on the same line as that which precedes
it.

IMHO, short code blocks are better in-lined :-
if (J==0) { K = 2 ; L = 3 }
But I've also noticed a lot of developers move it to the next line:

function myFunction
{

I also place a semicolon at the end of each line, although I see it's
also not mandatory.

Sometimes it is essential not to do so, unless you allow long lines or
break up the workings.

Is there a coding standard for Javascript?

There are many.

I prefer :-

Indentation by 2/3 spaces per block, and for later parts of split
statements; I prefer indentation to depend only on what has gone before
But that cannot always entirely be done without look-ahead; contrast
X = 1 + 2 X = 1 + 2 X = 1 + 2 ;
+ 3 Y = 3 Y = 3

Generally, white-space after each comma, around each semi-colon, around
each assignment operator, before each } and after each { and probably
vice-versa, and around // /* */ . Whitespace makes reading easier.
Extra whitespace if that makes similar parts of successive lines align
better internally.

Impose a strong (but not absolute) line-length limit so that lines
(almost) never get machine-wrapped later on. Because of the way I
display code on my site, my limit is 69 characters. For News, it should
be about 72.

Don't allow trailing whitespace. Unless the editor bars it, it can
easily creep in; it's very easy to remove with the sort of scripted
tools that one should have.

Don't repeat code if it can be put into a function without increasing
the overall size. Keep functions within a screenful where practical.
Use meaningful identifiers, but in moderation.

function RemoveMean(Aray) { var J, L, T = 0.0
for ( J = 0, L = Aray.length ; J < L ; J++ ) T += Aray[J]
T /= L ;
for ( J = 0 ; J < L ; J++ ) Aray[J] -= T
return Aray )

There's no need, IMHO, for longer identifiers within the function.

Never use a decimal point without a digit on each side.

It's a good idea to read the newsgroup and its FAQ. See below.
 
J

John G Harris

Tom said:
I'm starting to do more quantity of javascript coding and thought this
might be a good time to investigate code styling. I primarily develop
in Java and currently use the code styling techniques spelled out for
Java.

For example, in my code blocks ( {} ) I always place the starting brace
on the same line as the first line of code. For example:

function myFunction {

But I've also noticed a lot of developers move it to the next line:

function myFunction
{

Putting the opening bracket on the same line saves paper. If you're a
publisher then saving paper reduces costs and increases profits.

Programmers aren't publishers unless they are writing a textbook. Each
open curly bracket is matched by a close curly bracket, and they can be
a long way apart. It helps if it is easy to see which open bracket is
matched by which close bracket.

I also place a semicolon at the end of each line, although I see it's
also not mandatory.

I hope you understand semicolons better than that.

Third (and lastly) I also declare all Objects in first letter uppercase
and all member variables/functions in lowercase. For example:

function MyObject() {

var myFirstMemberVar;

function doSomething() {
....
}
}

Is there a coding standard for Javascript? Do my current practices seem
feasible?

Unlike Java there is no one company ramming code standards down your
throat. Look at standards for C, C++, Java, and C# and pick the bits
that suit you.

As others have said, being consistent is the most important thing.

John
 
J

John G Harris

function RemoveMean(Aray) { var J, L, T = 0.0
for ( J = 0, L = Aray.length ; J < L ; J++ ) T += Aray[J]
T /= L ;
for ( J = 0 ; J < L ; J++ ) Aray[J] -= T
return Aray )
<snip>

Here's another view of the same code :

function RemoveMean(Aray)
{
var J, L, T = 0.0;

for ( J = 0, L = Aray.length ; J < L ; J++ )
T += Aray[J];
T /= L ;
for ( J = 0 ; J < L ; J++ )
Aray[J] -= T;
return Aray;
)

Should the round bracket at the end be removed or changed to a curly
bracket? Now it's obvious.

John
 
P

petermichaux

However, we also recommend hungarian
notation for variables. This goes against our C# guidelines, but has a
reason: In JavaScript, objects are not strongly typed.

I played around with Hungarian notation in JavaScript and found it is
not a perfect fit because JavaScript is not strongly typed. For
example, when a function can take a variety of argument types and 'n'
is the prefix for nodes

function highlightElement(nElement) {
if (typeof nElement === "string) {nElement =
document.getElementById(nElement);}
nElement.style.background = "yellow";
}

So three out of five of these uses of "nElement" are for the case where
it is really strElement. The 'n' really specifes the type that the
function will convert to and use when it does its real work. So
although there is still meaning to the 'n', Hungarian notation doesn't
seem like a perfect fit.

Peter
 
D

Douglas Crockford

John said:
Here's another view of the same code :

function RemoveMean(Aray)
{
var J, L, T = 0.0;

for ( J = 0, L = Aray.length ; J < L ; J++ )
T += Aray[J];
T /= L ;
for ( J = 0 ; J < L ; J++ )
Aray[J] -= T;
return Aray;
)

Should the round bracket at the end be removed or changed to a curly
bracket? Now it's obvious.

I have two other problems with this. First, initial capitals should be reserved
for use with functions that require the new prefix. Upper case letters are so
FORTRAN.

Second, I want the for statements to have blocks. I have seen cases where a
statement was inserted into an antiblock:

for (j = 0; j < len; j += 1)
t += aray[j];
foo();

The expectation is that foo is called on every iteration, but it is only called
after the loop terminates. Errors like this can be very difficult to spot and
very expensive to find. It is possible that the next person to maintain this
code will not have your fantastic mental powers. Good programs should be written
to be read by ordinary humans.

JavaScript has only one number type, so the t = 0.0 can be written without the
decimal point.

Finally, computing the mean might be useful in other contexts, as might the
ability to subtract a scalar from an array. We can do some uncoupling, creating
opportunities for reuse.

function sum(aray) {
var j, len = aray.length, t = 0;

for (j = 0; j < len; j += 1) {
t += aray[j];
}
return t;
}

function mean(aray) {
return sum(aray) / aray.length;
}

function subtractScalar(aray, scalar) {
var j, len = aray.length;

for (j = 0; j < len; j += 1) {
aray[j] -= scalar;
}
return aray;
}

function removeMean(aray) {
return subtractScalar(aray, mean(aray));
}

Further stylistic improvement could be obtained by adapting these functions to
augment Array.prototype.

http://www.JSLint.com/
 
L

Laurent Bugnion

Hi,

I played around with Hungarian notation in JavaScript and found it is
not a perfect fit because JavaScript is not strongly typed. For
example, when a function can take a variety of argument types and 'n'
is the prefix for nodes

function highlightElement(nElement) {
if (typeof nElement === "string) {nElement =
document.getElementById(nElement);}
nElement.style.background = "yellow";
}

So three out of five of these uses of "nElement" are for the case where
it is really strElement. The 'n' really specifes the type that the
function will convert to and use when it does its real work. So
although there is still meaning to the 'n', Hungarian notation doesn't
seem like a perfect fit.

Peter

Yes. This case is also described in our guidelines. In this case we
recommend using

function highlightElement ( element )
{
...
}

or even (if it increases readibility enough to justify it)

function highlightElement ( element )
{
if ( typeof( element ) == "string" )
{
var strElement = element;
// ...
}
}

HTH,
Laurent
 
P

petermichaux

Laurent said:
Hi,



Yes. This case is also described in our guidelines. In this case we
recommend using

function highlightElement ( element )
{
...
}

or even (if it increases readibility enough to justify it)

function highlightElement ( element )
{
if ( typeof( element ) == "string" )
{
var strElement = element;
// ...
}
}

Hi Laurent,

Thanks for the reply. Is this the only situation you found that is a
problem or are there other exceptions to making Hungarian notation work
in JavaScript?

Is there a URL for your guidelines?

Thanks,
Peter
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Sat, 30 Sep 2006 17:57:10 remote, seen in
Douglas Crockford said:
JavaScript has only one number type, so the t = 0.0 can be written without the
decimal point.
as 00 ? :)

Indeed it can be. But, although there is only one type of number, there
is in almost all cases a clear distinction between quantities which are
necessarily always integer by intent and those which, while they may
sometimes have exact integer values, are fundamentally real and are
expected to take general values in the course of the work.

When the second type of quantity is initialised to an integer value,
adding ".0" is effectively a cheap form of comment - and, if it is added
consistently in such cases, so is not adding it for "integers".

The forms .0 and 0. are rightly deprecated by such as IUPAP & SUNAMCO.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top