Title: Javascript clarity of purpose
Tags: javascript;coding-style
Question: Javascript usage has gotten remarkably more sophisticated and powerful in the past five years. One aspect of this sort of functional programming I struggle with, esp with Javascript’s peculiarities, is how to make clear either through comments or code just what is happening. Often this sort of code takes a while to decipher, even if you understand the prototypal, first-class functional Javascript way. Any thoughts or techniques for making perfectly clear what your code does and how in Javascript?
I've asked this question elsewhere, but haven't gotten much response.


Here is another answer: Don't forget that when you write (or come across) a particularly esoteric bit of code, you should probably consider explaining what it's doing (and why it's doing it) with a quick comment, which will help anyone else who has to read the code, but who might not be literate enough in the language to understand what's actually happening.
Comment for this answer: But see, that is my point - to someone not familiar with JavaScript, there are too many things that would need to be pointed out, since it differs from some languages significantly; my code, which I can completely understand, shouldn't so commented that it becomes a substitute for language knowledge

Here is another answer: @Jason Bunting
I've got to say I disagree that "only a decently deep knowledge" of the ins and outs of javascript will help one's understanding of your copy() example. Comments along the lines of  "deep copy" or "recursive call to copy object properties" and so forth can quickly elucidate for the programmer who isn't green behind the ears but doesn't know all the particulars of Javascript's peculiarities.
I know there are a number of important concepts to pick up before you can really know Javascript, but that doesn't mean code can't be clearer at a glance.
Comment for this answer: I agree with JesDaw. Comments may not be *necessary* to understand your code, but could help the next schlep who came along to more quickly understand it. I don't want to have to sit and study someone else's code in order to maintain it if a couple of comments would make it instantly clear.
Comment for this answer: Again, I am not saying that it shouldn't be commented; did I say that? No, I am simply saying that there is a line between some comments to help the reader understand the intent of the code and comments that have to actually teach people JavaScript. I don't feel I should have to do the latter.

Here is another answer: My opinion is twofold:
Learn the language. JavaScript closures and {key: {function}} are not that hard to understand. In fact, it's a pretty common dialect.
Learn the framework. jQuery, prototype, etc. are all great frameworks that tries to follow a principle of regularity and homogeneity along all the API. If you grasp this way of doing things in your own JavaScript code, things become clear.
For example, I recently needed a method for applying custom behavior to some inputs. Instead of going functional style, I extended all the <input&gt; elements with my method (I'm using prototype), which goes in line with the rest of the prototype stuff. If one keeps these kinds of principles in mind when developing, most of the code becomes pretty straightforward.
My biggest complaint for JavaScript is to know how to organize my .js files, but that's another story.

Here is another answer: I think it is one of the aims of those frameworks like prototype or jQuery to hide most of the JavaScript stuff. Since it is not easy to understand it, they are designed to be as easy as can be.
Therefore if you use such frameworks JavaScript gets cleaner. What I do is to write many many comments, use a lot of whitespace and lines and so on. But those {{function(){... stories remain.
Comment for this answer: Lots of whitespace?! I don't know how that makes things "perfectly clear" (which is what the OP asked) - it may make it easier on the eyes, but not necessarily clear...JavaScript is as easy to understand as any other language, people just need to spend time learning it instead of ignoring it.

Here is another answer: Format your code. If you have no idea how to use it - rely on IDE ( NetBeans or WebStorm has it inbuilt ) or JS Beautyfier ( if you are still coding in Notepad, for some reason. )
Use general principles for clean code. Use brackets, stick to one code convention, use comprehensible naming scheme, comment sparingly, avoid global variables, deep nesting, long functions and esoteric code.
Make sure your IDE can recognize your code. Often this means you have to scrap module pattern aka power constructor var module = ( function () { ... } )(); in favor of classic constructor Module = function () { ... }; Module.prototype.method1 = function () { ... };
Declare vars in the beginning of function, to avoid well known problems with variable hoisting.
Replace this in constructors with better name. Which somehow shows actual object purpose. function Car() { _car = this; _car.accelerate = function () { ... }; }
Write cross-browser code for modern browsers, and, if you need support for old crap like IE8 and below - use jQuery or other framework. Avoid doing browser detection anywhere after your initializer function, if possible.
Use JS Doc, when you can - i.e. if your IDE or repo-browser supports it.
Write for debug, when your code is really complex. i.e.: do not function() { return { huge chunks of code, do not abuse chaining, do not inline things that might break.
Do not use eval, neither standalone, nor implicit eval in setTimeout or addEventListener.

Here is another answer: The use of a common library is one thing, but I think a lot of "getting" JavaScript is simply spending time writing it. Things that may seem esoteric will slowly become mundane. This is true of just about any language or framework.
Many of the idioms used in JavaScript, such as anonymous functions, literal syntax, etc. only seem strange when you are first exposed to them. I think the same rules for writing understandable C#/Java/C++/VB/etc. code apply to JavaScript - use variable names that have semantic meaning, write comments that help someone understand intent and acknowledge assumptions, be explicit, etc.
Now, if you are really asking "how can I make JavaScript understandable to someone that is not familiar with it?" you have another issue - JavaScript is JavaScript and developers just have to do the hard work of learning it before they can be proficient in it and become "at one" with it.
For example, this function may seem very strange to those that are not familiar with JavaScript, but for me (and I am certain many others) it isn't that hard to figure out:
// comments are not included *on purpose* for illustrating
// my point about the need for language knowledge
function copy(obj) {
return new (function(o) {
for(var property in o) {
if(o[property].constructor == Array) {
this[property] = [];
for(var i = 0; i < o[property].length; i++) {
this[property][i] = new arguments.callee(o[property][i]);
}
} else if(o[property].constructor == Object) {
this[property] = new arguments.callee(o[property]);
} else {
this[property] = o[property];
}
})(obj);
The fact that this function has a name helps the casual reader know what it does, but to really understand what it is doing, one has to have an understanding of why this function might be necessary, how JavaScript object properties can be referenced, what data types JavaScript supports, how constructor functions work, how anonymous functions work, etc. Only a decently deep knowledge of those things are going to help (or a library that has literally everything but the kitchen sink).
UPDATE: To those that say comments in the above sample would lend help to the developer attempting to understand it - obviously. Comments are useful and I think that is a given. The above sample code was meant to illustrate multiple JavaScript-specific idiosyncrasies that are only going to be understood by someone with deep enough knowledge about the language.
As I said in the comments on someone else's answer, my code, which I can completely understand based on my JavaScript knowledge, shouldn't need to be so commented that it becomes a substitute for language knowledge. I shouldn't have to explain, for example, where an anonymous function is or that I am using one in the above code as an anonymous constructor function and that it will alter the perceived standard behavior (to C# and Java devs) of the this keyword, all things that are going to confuse lesser JavaScript developers.

Here is another answer: One good way to do this is to use the principles of Unobtrusive JavaScript to separate concerns. The use of jQuery as suggested by Sebastian used this principle.
Unobtrusive JavaScript

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 7, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2008:00:11/11/08', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><coding-style>', 'Title': 'Javascript clarity of purpose', 'ViewCount': 418, 'id': 282184, 'user_AboutMe': '', 'user_AccountId': 3123.0, 'user_DisplayName': 'JesDaw', 'user_Reputation': 151.0, 'user_Views': 58.0, 'user_id': 4440.0}}