Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write readable Javascript

In JavaScript, the standard rules for code formatting don't seem to cut it. You still end up with messes of });}); all over the place and I don't believe I even know of established rules for the correct indention of anonymous functions declared as arguments to other functions.

In short, I have trouble reading my own JavaScript, and I bet I'm not alone.

I think the idea that I am coming around to is to just not define functions within other functions. Write every function with a name and as a child to the script tag. When you need to pass functions around, use their names. Of course, this makes it a lot harder to use closures [edit: you cannot use closures at all if you write your code that way]. Also, this might cause problems with memory management?

Anyone else have thoughts on this?

like image 638
Joe Avatar asked Nov 02 '11 20:11

Joe


People also ask

Is JavaScript readable?

JavaScript has been evolving into a more readable language. There is no doubt about that, and there is no harm either. Software development is a dynamic market where teams change constantly, meaning that the code needs to be readable for newcomers.

Why is JavaScript so hard to read?

Unique Syntax and Indentation Makes JavaScript Hard To Read. Arguably, one of JavaScript's weaknesses is its syntax. Its object literals, for instance, require you to use braces in a different way than other languages. Like any other programming language, there are many different ways to write your code.


2 Answers

I bet you should just follow already established coding standards.

You may follow coding standard for one of two best JavaScript frameworks:

  • Mootols (coding standard here), or
  • jQuery (coding standard here),

Basically use tabs instead of spaces (this may be difficult for some, but I believe is established standard for JS), avoid unnecessary spaces (eg. in ) { in function definition space is not welcome and should probably look like: ){), etc.

PS. It is my personal > opinion < that MooTools & jQuery are 2 the best JS frameworks.

like image 136
Tadeck Avatar answered Sep 24 '22 19:09

Tadeck


You need to format your code in order to be readable. And always while typing JS use IDE features to format code and each new command put into new row. Then you won't have a problems.

You can use Online JavaScript beautifier for your existing javascript.

like image 43
Senad Meškin Avatar answered Sep 21 '22 19:09

Senad Meškin