What is the best-practice casing style for javascript? Why? - javascript

One aspect of javascript that it's hard to find information on is casing practices. By casing practices, I mean what casing style (ie. camel-case, pascal-case, etc) should be used for what elements (Constructors, private functions, public functions).
The only rule I've heard was from a Douglas Crockford lecture on YUI theater, stating that constructors should be the only functions that start with an uppercase letter.
Beyond that there doesn't seem to be many casing standards that people follow in javascript.
Does anyone know any casing best practices for javascript, and why it's reasonable to use them?
Also do you follow a casing style with your .js files?

I prefer PascalCase for constructors and camelCase for everything else. That's the style that JS standard library uses and well... every JS framework I've seen so far :)
And I use all_lowercase naming convention for all files served from web. There are some case-insensitive file systems out there.

The core language uses InitialCaps for constructors (e.g. Object, Date, Number, RegExp) and camelCase for methods and properties (e.g. something.toString(), quantity.valueOf(), regexp.ignoreCase). This convention is also followed in the DOM specifications and implementations (e.g. HTMLElement.setAttribute()). So it makes the most sense to adopt the same convention, or you finish up with a horrendous mishmash of styles like:
var number_of_fish_requested = document.getElementById("fish").value;
var fish_count = parseInt(number_of_fish_requested, 10);
which just becomes utterly confusing, not only to type but, much more importantly, to read.
(You spend more time reading code, trying to debug or modify it, than you ever do writing it in the first place.)

What I have seen so far is a very large diversity of casing standards.
As far as I'm concerned, I use C# styling for writing my JavaScript code. I use classes a lot (well functions as classes, and usually don't have independent functions.)
So, I use PascalCase for class names, public methods, properties and all global variables and camelCase for arguments, local variables and private functions. This somehow reflects my common environment, helping to distinguish the variable scopes.
I also tend to keep my class functions in a separate file with the same name as my ClassName (ClassName.js, ClassName.min.js).
This was about my approach.
I also noticed that Java programmers, follow the Java rules (and the writing style resembles the Java language.) Ruby on Rails programmers follow their own naming standards such as underscore_separated_var_name.
Further, as you mentioned, there is a tendency to use pascalCase a lot in naming in very popular frameworks whose authors come from different communities like Linux/Open source community and Microsoft developers (jQuery, knockout.js, JSJaC, etc.)
I should note that none of these methods are wrong or right, when it comes to JS. The primary purpose of your naming conventions and file structuring is the readability. If you are consistent then you in future and your fellow developers will quickly understand and get on with your code.

I prefer camelCase for everything except for constructors. The reason (and I believe this is why Mr. Crockford suggested this as well) is because in other languages, such as Java, the convention is capitalize your classes, which is what constructors are used for.
That is my $0.02.

All lower case with underscore separators is the easiest to read; it follows natural language. "Best" will get you in to a holy war; the reality is case doesn't matter as much as other design issues but it's an easy topic to polarize.
ALongButNotReallyReadableIdentifier
an_even_longer_but_completely_readable_identifier

The accepted answer is true but there are some exceptions.
In window.JSON and window.XMLHttpRequest the term is capitalized.
Also most people use PascalCase for enum type objects in Javascript and capitalized values within. Sometimes namespaces are done in PascalCase also.
example:
MyCompany.Web.UI.MyComponent.ThemeOption = { BLACK: 0, SILVER: 1, BLUE: 2}

Related

Is there a set of restrictions I can use to simulate functional programming in JavaScript?

I was watching a talk on clean code by Misko Hevery, and he mentioned trying to write a program with no if statements in them (well, as few as humanly possible) in order to simulate working on... Smalltalk or some such language, where polymorphism is preferred over inline conditional behavior.
To my limited understanding, functional programming is hard for only-imperative-so-far programmers like me - because our state changing methodologies don't have a way to be expressed in functional programs. A function only takes a value and returns a value and knows nothing about state.
I have also seen JS being hailed as being able to support a functional model.
So is there a simple set of restrictions, similar to my first paragraph, which will enable me to try out the functional paradigm in a language I know and love - rather than learn a full new language (I'll do that eventually but I want to try the ethos right now)?
There are two meanings to the term "functional programming".
The first meaning is the ability of a program to manipulate functions. Not all languages can do this but javascript is one of the languages that can. Languages that can assign functions to variables, pass functions to arguments and return functions are called functional programming languages so javascript is functional as is.
In this sense, if you look at any modern javascript code with prevalent use of callbacks then you're already doing functional programming.
The second meaning of functional programming is the style of programming where the primary method of program composition is functions rather than variables. In this sense almost any language can be used in a functional style by avoiding variable assignments and loop structures (use recursion instead).
When you look at the functional community, what they mean by functional is the first meaning plus a very strong version of the second meaning -- that is, variables are not only avoided but banned. Languages like Haskell don't have the concept of variables. To handle side-effects and mutable state like I/O they use a concept called monads.
You don't have to go that far. Classical functional languages like Lisp and Forth allowed variables. You just have to avoid them where possible.
Lisp and Forth style functional programming is heavily driven by processing lists/arrays without assigning anything to temporary variables. To some people, this style is easier to read. Where in imperative style you'd do this:
var a = [1,2,3];
var b = 0;
for (var i=0;i=a.length;i++) {
b += a[i] * 2;
}
// result is in b
in functional style you'd do this:
[1,2,3].
map(function(x){return x*2}).
reduce(function(x,y){return x+y},0);
Conceptually, functional style makes it look like you're applying filters to the array instead of iterating through the array. If you've ever used command line tools like grep then you'd find this concept very familiar.
Notice that we haven't introduced any variable assignments at all in the functional style.
The three core array methods/functions in the functional style are: map, reduce and filter. With them you can avoid something like 90% of for-loops.
Great question.
For an in-depth answer, check out this classic (and awesome) paper by John Hughes -- Why Functional Programming Matters.
First, Hughes explains what functional programming is not about, and cites some weak arguments that proponents of FP use. Good stuff (but too long to quote here).
Second, Hughes explains what FP is about:
It is now generally accepted that modular design is the key to successful programming, and recent languages such as Modula-II [6] and Ada [5] include features specifically designed to help improve modularity. However, there is a very important point that is often missed. When writing a modular program to solve a problem, one first divides the problem into subproblems, then solves the subproblems, and finally combines the solutions. The ways in which one can divide up the original problem depend directly on the ways in which one can glue solutions together. Therefore, to increase one’s ability to modularize a problem conceptually, one must provide new kinds of glue in the programming language. Complicated scope rules and provision for separate compilation help only with clerical details — they can never make a great contribution to modularization.
We shall argue in the remainder of this paper that functional languages provide two new, very important kinds of glue. We shall give some examples of programs that can be modularized in new ways and can thereby be simplified. This is the key to functional programming’s power — it allows improved modularization. It is also the goal for which functional programmers must strive — smaller and simpler and more general modules, glued together with the new glues we shall describe.
(emphasis mine)
So to get back to the original question, in order to do FP in Javascript, you'll want to build programs by implementing separate modules, then gluing them together. Javascript comes with some nice glue, and you can build even more glue on your own -- check out combinators.
You should try to avoid features that prevent you from using glue to combine modular pieces of code, for example:
mutable state -- especially if it's global
statements -- you can't pass while-loops as function arguments
some kinds of syntax, such as operators or property access -- you can't assign + to a variable or pass it as an argument
(These issues can, of course, be mitigated to a certain extent -- check out Javascript FP libraries for examples.)
On the other hand, features that aren't functions -- such as classes, objects, inheritance, prototypes, etc. -- don't necessarily stop you from using Javascript's glue, so there's no reason, from an FP standpoint, not to use them.

What are the key differences between JavaScript and ActionScript 3?

I know both languages are from the same ECMA-262 standard. It seems that the two are becoming very similar with JavaScript adding event listeners for core Object instances through methods like freeze and seal in EMCAScript-262 5th edition and such. I was wondering what the differences are?
First of all ActionScript 3 and JavaScript are both defined in ECMA-262 so they have a lot in common. Both languages feature prototype inheritance for instance. It is however not correct that ActionScript fully implements ES4.
ActionScript implements a couple of features that are not defined in ECMA-262 and some -- but definitely not all -- of ES4.
So what does AS3 add to ECMA-262? Those are also the differences to JavaScript:
Dynamically and statically typed code
Packages, Classes and Interfaces
Standard OO inheritance model (not prototype based, statically typed)
uint and int datatype
E4X (ECMA-357)
Type-safe conditional compilation (ES4)
Vector.<T> datatype (ES4)
Maybe I have forgotten some features. I am not sure if XML, XMLList etc. are already defined in 262 or came with 357.
The key difference however is the standard library. JavaScript comes with a couple of predefined classes like DOMElement and browser dependent additions. ActionScript has a fairly large standard library with features like video streaming and is consistent over all platforms.
I've been programming in both ActionScript and Javascript, and from a less-technical standpoint, I see two main differences.
1) JavaScript is more powerful. You are allowed to do much more with the language because it does not have a "compiler" or types. There are some great frameworks out there like ExtJS and jQuery that try and simplify things for you, but even with them, you are really allowed to do an amazing amount of damage if you want to.
2) ActionScript is much more confining and hence, much easier to maintain. Adobe did a lot of work to keep you out of the difficult parts of ECMAScript. ECMAScript Objects, prototypal inheritance, and closures are three concepts that you really don't need to understand to program in ActionScript. You just need to understand how to use Adobe's "Class" object.
For simple uses, I prefer JavaScript. However, once the project gets large, it depends who you are coding for. If I had a team of 5 developers programming at a scrappy start-up, I'd choose JavaScript in a heartbeat. However, in the girth of a large corporation, or academia, you might be safer relying on Adobe's platform.
Hope that helps.
One is type Safetly. Actionscript requires that you set a type for all objects, and JavaScript doesn't (for that matter, in JavaScript, one variable may be one type and then immediately set to another type).
Actionscript is object oriented. Although you can sort of have this in JavaScript, Actionscript allows for object inheritance, etc.
Essentially the main difference I find is that ActionScript is more a verbose statically-typed class-based language where as javascript is a prototypal language.
Unfortunately there is no type-inference in ActionScript so using Flex Builder gives a warning every time you leave something untyped which I find unnecessary and overly verbose, not only does it make it more verbose than javascript but I find equivalent code to be more verbose than C#.
However the extra verbosity does have yield perf improvements and extra type safety at compile-time. Unfortunately this also adds to build time quite significantly, in Java Script apps of any size I'm used to instant feedback whereas my last ActionScript project had build time exceeding 2 minutes.
From a developer point of view, what matter most:
1) Javascript is not really OOP, it has NO super keyword, which means if you override( by any means ) something, you can't call it through super, and this is the deal breaker for complex programs for which OOP is the key, and Actionscript3 is all OOP, you can have millions line of Actionscript3 code working together, and well maintained.
2) Actionscript3 runs in Flash Player which has only one implementation from Adobe, this means it's consistent all the time, all browsers( as long as installed Flash Player), but Javascript runs in browsers directly, but each browser has its own implementation, which means your Javascript code has to be tested against all targeted browsers to ensure working.
The key differences are that ActionScript 3 supports both class-based inheritance and prototypal inheritance, enforces namespace bindings between class names and file names, and does not support some global JavaScript methods such as eval. Fortunately, you can do several things to bridge the gap.
You can globally set the namespace using ES for ECMAScript or AS3 for ActionScript 3:
use namespace ES;
use namespace AS3;
If you are using the AS3 namespace, any method override must use the AS3 namespace
and the override attribute.
If you are not using the AS3 namespace, you can use the prototype methods and propertyIsEnumerable.
You can selectively use the AS3 namespace version of a property or method in a dynamic function:
var nums:Array = new Array(1, 2, 3);
nums.AS3::pop();
trace(nums); // output: 1,2
To turn off class based inheritance, you can also use the following compiler options:
compc -as3=false -strict=false -es=true
import *
class foo
{
dynamic function foo()
{
}
}
If you do not use the AS3 namespace, an instance of a core class inherits
the properties and methods defined on the prototype object.
If you decide to use the AS3 namespace, an instance of a core class inherits the
properties and methods defined in the class definition.
Here is a common features between ECMAScript-4 and ECMAScript-2017 or later:
Feature ES4/ES6+ ES4 Only
Rest parameter ☑
Destructuring ☑
ByteArrays ☑
Class ☑
Interface ☑
Static fields ☑
Parameter default ☑
Rest Parameters ☑
Bound methods ☑
dynamic this value ☑
multiple catch clauses ☑
short-circuit-and (&&=) ☑
short-circuit-or (||=) ☑
Type Annotations ☑
References
Simulating AS3 language features in JavaScript using AMD and ES5
JavaScript 2 Draft
ECMAScript 4th Edition[proposed]:Predefined Types and Objects
The New Browser War
ECMAScript 1-on-1
The Trouble with JavaScript: JavaScript has no Class
What's New in ECMAScript-4
David Flanagan on JavaScript 2
JavaScript 2 and the Future of the Web
Writing Classes
Faster byte array operations with ASC2
Managing event listeners
frankly it's not the same, cuz action script is loaded with EMQJ24, the new language for high development website. while JS still with it EMCA22, the difference between those are the style and format of the code. and also action script are ages enough, that's why most of programmer nowdays using CSX01 updated language from cSS,it can recognize all type off language without any line.

Capitalization convention for JavaScript objects

I know this question has no answer, but I'm curious to know what other people think.
In a language like Java, it's a convention to begin classes with capital letters, and objects with lowercase letters. But what about JavaScript, where everything is an object?
I've seen some people suggest capitalizing only objects that are treated as classes; i.e. function objects with a prototype, that are intended to be used with the new operator. Instances of those objects would be lowercased.
That sounds logical. But what do you do about "global objects", where there's only one instance? Most people seem to capitalize these (for example, Math or Ext.History). This intuitively feels right, but it's hard to justify it with a consistent rule.
And what about objects that are used as namespaces? These seem to be all over the map: YUI, Ext.util, jQuery, etc.
Please provide secular rationalizations for your heart-felt religious views.
You can follow this Google JavaScript Style Guide
In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
As recommended by Douglas Crockford:
"Constructor functions that must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is missing, so the capitalization convention is an important defense."
https://www.crockford.com/code.html
The convention is that there is no convention. Do what you want, just be consistent. I suggest follow Java style and ignore whatever convention the library (dojo, Ext, YUI, $, etc) you happen to be using is following.
I agree with the capitalization of functions that define "classes" (air-quotes used) that in turn will be instanciated later using the new operator.
But that's it. Global objects are just global. Name them what you want.
All I would make sure is that they are unique and descriptive enough that they won't be overwritten accidentally by another developer at a later date.

What lessons can be learned from the prototype model in javascript?

The question is from a language design perspective.
I should explain a little about the situation. I am working on a javascript variant which does not support prototypes, however it is overdue a decent type system (most importantly support for instanceof). The ecmascript spec is not important, so i have the freedom to implement something different and better suited.
In the variant:-
You do not declare constructors with function foo(), rather constructors are declared in template files, which means constructors exist in a namespace (detirmined by the path of the file)
Currently all inheritance of behaviour is done by applying templates which means all shared functions are copied to each individual object (there are no prototypes afterall).
Never having been a web developer, this puts me in the slightly bizarre position of never having used prototypes in anger. Though this hasn't stopped me having opinions on them.
My principal issues with the prototype model as i understand it are
unnecessary littering of object namespace, obj.prototype, obj.constructor (is this an immature objection, trying to retain ability to treat objects as maps, which perhaps they are not?)
ability to change shared behaviour at runtime seems unnecessary, when directly using an extra level of indirection would be more straight forward obj.shared.foo(). Particularly it is quite a big implementation headache
people do not seem to understand prototypes very well generally e.g. the distinction between a prototype and a constructor.
So to get around these my idea is to have a special operator constructorsof. Basically the principal is that each object has a list of constructors, which occasionally you will want access to.
var x = new com.acme.X();
com.acme.Y(x,[]); // apply y
(constructorsof x) // [com.acme.Y,com.acme.X,Object];
x instanceof com.acme.X; // true
x instanceof com.acme.Y; // true
All feedback appreciated, I appreciate it maybe difficult to appreciate my POV as there is a lot i am trying to convey, but its an important decision and an expert opinion could be invaluable.
anything that can improve my understanding of the prototype model, the good and the bad.
thoughts on my proposal
thanks,
mike
edit: proposal hopefully makes sense now.
Steve Yegge has written a good technical article about the prototype model.
I don't think your issues with the prototype model are valid:
unnecessary littering of object namespace, obj.prototype, obj.constructor
prototype is a property of the contructor function, not the object instance. Also, the problem isn't as bad as it sounds because of the [[DontEnum]] attribute, which unfortunately can't be set programatically. Some of the perceived problems would go away if you could.
is this an immature objection, trying to retain ability to treat objects as maps, which perhaps they are not?
There's no problem with using objects as maps as long as the keys are strings and you check hasOwnProperty().
ability to change shared behaviour at runtime seems unnecessary, when directly using an extra level of indirection would be more straight forward obj.shared.foo(). Particularly it is quite a big implementation headache
I don't see where the big implementation headache in implementning the prototype chain lies. In fact, I consider prototypical inheritance conceptually simpler than class-based inheritance, which doesn't offer any benefits in languages with late-binding.
people do not seem to understand prototypes very well generally e.g. the distinction between a prototype and a constructor.
People who only know class-based oo languages like Java and C++ don't understand JavaScript's inheritance system, news at 11.
In addition to MarkusQ's suggestions, you might also want to check out Io.
It might just be easier to try a few things with practical code. Create the language with one simple syntax, whatever that is, and implement something in that language. Then, after a few iterations of refactoring, identify the features that are obstacles to reading and writing the code. Add, alter or remove what you need to improve the language. Do this a few times.
Be sure your test-code really exercises all parts of your language, even with some bits that really try to break it. Try to do everything wrong in your tests (as well as everything right)
Reading up on "self", the language that pioneered the prototype model, will probably help you more than just thinking of it in terms of javascript (especially since you seem to associate that, as many do, with "web programming"). A few links to get you started:
http://selflanguage.org/
http://www.self-support.com/
Remember, those who fail to learn history are doomed to reimplement it.

Object Oriented Javascript best practices? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm finding myself coding a big project in Javascript. I remember the last one was quite an adventure because hacky JS can quickly becomes unreadable and I want this code to be clean.
Well, I'm using objects to construct a lib, but there are several ways to define things in JS, implying important consequences in the scope, the memory management, the name space, etc. E.G :
using var or not;
defining things in the file, or in a (function(){...})(), jquery style;
using this, or not;
using function myname() or myname = function();
defining methods in the body of the object or using "prototype";
etc.
So what are really the best practices when coding in OO in JS ?
Academic explanations really expected here. Link to books warmly welcome, as long as they deal with quality and robustness.
EDIT :
Got some readings, but I'm still very interested in answers to the questions above and any best practices.
Using `var` or not
You should introduce any variable with the var statement, otherwise it gets to the global scope.
It's worth mentioning that in strict mode ("use strict";) undeclared variable assignments throws ReferenceError.
At present JavaScript does not have a block scope. The Crockford school teaches you to put var statements at the beginning of the function body, while Dojo's Style Guide reads that all variables should be declared in the smallest scope possible. (The let statement and definition introduced in JavaScript 1.7 is not part of the ECMAScript standard.)
It is good practice to bind regularly-used objects' properties to local variables as it is faster than looking up the whole scope chain. (See Optimizing JavaScript for extreme performance and low memory consumption.)
Defining things in the file, or in a `(function(){...})()`
If you don't need to reach your objects outside your code, you can wrap your whole code in a function expression—-it's called the module pattern. It has performance advantages, and also allows your code to be minified and obscured at a high level. You can also ensure it won't pollute the global namespace. Wrapping Functions in JavaScript also allows you to add aspect-oriented behaviour. Ben Cherry has an in-depth article on module pattern.
Using `this` or not
If you use pseudo-classical inheritance in JavaScript, you can hardly avoid using this. It's a matter of taste which inheritance pattern you use. For other cases, check Peter Michaux's article on JavaScript Widgets Without "this".
Using `function myname()` or `myname = function();`
function myname() is a function declaration and myname = function(); is a function expression assigned to variable myname. The latter form indicates that functions are first-class objects, and you can do anything with them, as with a variable. The only difference between them is that all function declarations are hoisted to the top of the scope, which may matter in certain cases. Otherwise they are equal. function foo() is a shorthand form. Further details on hoisting can be found in the JavaScript Scoping and Hoisting article.
Defining methods in the body of the object or using "prototype"
It's up to you. JavaScript has four object-creation patterns: pseudo-classical, prototypical, functional, and parts (Crockford, 2008). Each has its pros and cons, see Crockford in his video talks or get his book The Good Parts as Anon already suggested.
Frameworks
I suggest you pick up some JavaScript frameworks, study their conventions and style, and find those practices and patterns that best fit you. For instance, the Dojo Toolkit provides a robust framework to write object-oriented JavaScript code which even supports multiple inheritance.
Patterns
Lastly, there is a blog dedicated to explore common JavaScript patterns and anti-patterns. Also check out the question Are there any coding standards for JavaScript? in Stack Overflow.
I am going to write down some stuffs that I read or put in application since I asked this question. So people reading it won't get frustrated, as most of the answers are RTMF's in disguise (even if I must admit, suggested books ARE good).
Var usage
Any variable is supposed to be already declared at the higher scope in JS. So when ever you want a new variable, declare it to avoid bad surprises like manipulating a global var without noticing it. Therefore, always use the var keyword.
In an object make, var the variable private. If you want to just declare a public variable, use this.my_var = my_value to do so.
Declaring methods
In JS, they are numerous way of declaring methods. For an OO programmer, the most natural and yet efficient way is to use the following syntax:
Inside the object body
this.methodName = function(param) {
/* bla */
};
There is a drawback: inner functions won't be able to access "this" because of the funny JS scope. Douglas Crockford recommends to bypass this limitation using a conventional local variable named "that". So it becomes
function MyObject() {
var that = this;
this.myMethod = function() {
jQuery.doSomethingCrazy(that.callbackMethod);
};
};
Do not rely on automatic end of line
JS tries to automatically add ; at the end of the line if you forget it. Don't rely on this behavior, as you'll get errors that are a mess to debug.
First ought to read about the prototype-based programming so you know what kind of beast you're dealing with and then take a look at JavaScript style guide at MDC and JavaScript page at MDC. I also find best to force the code quality with a tool, ie. JavaScript Lint or other variants.
Best practices with OO sounds more like you want to find patterns than concentrate on code quality, so look at Google search: javascript patterns and jQuery patterns.
Speed up your JavaScript
You might want to check out Secrets of the JavaScript Ninja by John Resig (jQuery). "This book is intended to take an intermediate JavaScript developer and give him the knowledge he needs to create a cross-browser JavaScript library, from the ground, up."
The draft is available through the publisher:
http://www.manning.com/resig/
Douglas Crockford also has some nice JavaScript articles on his homepage:
http://www.crockford.com/
I often feel like the only guy here who uses MooTools for my javascript.
It stands for My Object Oriented Tools, mootools.
I really like their take on OOP in javascript. You can use their class implementation along with jquery too, so you don't have to ditch jquery (though mootools does it all just as well).
Anyway, give the first link a good read and see what you think, the second link is to the mootools docs.
MooTools & Inheritance
MooTools Classes
Here's a book that covers most of the bases:
Object Oriented Javascript for high quality applicatons and libraries

Categories