Sei sulla pagina 1di 6

JavaScript guidlines

Style guidelines
Line breaking: When a line reaches maximum length it must be manually split into two or more lines. Line breaking is done after an operator and the next line is indented two levels. Blank lines: An often overlooked aspect of code style is the use of blank lines. In general code should look like a series of paragraphs rather than one continuous blob of text. Blank lines should be used to seperate related lines of code from unrelated lines of code. In general it is a good idea to also add blank lines: Between methods Between the local variables in a method and its first statement Before a multiline or single!line statement Between logical section inside a method to improve readability Naming "ariable and functions: #ames are always camel$ase and should begin with a noun. Beginning with a noun helps to differentiate between variables and functions which should begin with a verb. %xamples: var count & '() var my#ame & *+o,) $onstants: -se all uppercase letters with underscores to seperate words. %xample: var .A/0$1-#2 & '() $onstructors: 2hese are formated using 3ascal$ase. this helps to differentiate constructors from normal functions. $onstructor names are typically nouns as they are used to create instances of a type.

Source: Maintainable JavaScript by Nicholas Zakas (OReilly) Copyright !" # $%&'"' (($') %*&'

%xample: function 3ersion4name56 this.name & name 7 Literal Values 8trings: 8ingle 9uotes are prefered because it allows clean html to be encapsulated in a :avascript string. #umbers: #umbers literals should not be specified with a hanging or leading decimal point. 4'(. or .'(5 2he use of the octal notation is forbidden 4('(5 #ull: 2he special value null is often misunderstood and confused with undefined. 2his value should be used in :ust a few cases: 2o initiali;e a variable that may later be assigned to an ob:ect value. 2o compare against an initiali;ed variable that mey or may not have an ob:ect value. 2o pass into a function where an ob:ect is expected. 2o return from a function where an ob:ect is expected. 2here are also some cases where null should not be used: <o not use null to test wheter an argument was supplied <o not test an uninitiali;ed variable for the value null. -ndefined: 2he special value undefined is fre9uently confused with null. 3art of the confusion is that null && undefined is true. =owever these two values have two very different uses. "ariables that are not initiali;ed have an initial value of undefined which essentially means that the variable is waiting to have a real value. 8etting a value to null initially indicates your intent for that variable) it should eventually contain an ob:ect. Comments When to comment is a topic that always fosters great debate among developers. 2he general guidline is to comment when something is unclear and not to comment when something is apparent from the code itself. <ifficult to understand code should always be commented. Another good time to comment code is when the code appears to have an error but does not.

Source: Maintainable JavaScript by Nicholas Zakas (OReilly) Copyright !" # $%&'"' (($') %*&'

Variables, functions and declarations "ariable declarations: "ariable declarations are accomplished by using the var statement. 2he recomendation is to hava all your local variables defined as the first statements in a function. >unction declarations: >or code readability always try to declare functions before they are used immediatly after variable declarations. Immediate function invocation: 2o make it obvious that an immeditate function invocation is taking place put parentheses around the function. %xample: var value & 4function456 return 6 mess9ge: *hi, 7 7455) Equality %9uallity in :avascript is tricky due to type coercion. 2ype coercion causes variables of a specific type to be converted automatically into a different type for a particular operation to succeed which can lead to some unexpected results. Because of type coercion avoiding ?& and && at all is recommended. Instead use &&& adn ?&&. 2hese operators perform comparison without type coercion.

Programming practices
Avoid globals $reating globals is considered bad practice in general and is specifically problematic in a team development environment. @lobals creat a set of nontrivial maintenance issues for code going forward. 2he more globals the greater the possibility that errors will be introduced due to the increasing likelihood of a few common problems. As a means to avoid globals namespaces should be used. A namespace is simply a logical grouping of functionallity under a single propery on the global. @rouping
Source: Maintainable JavaScript by Nicholas Zakas (OReilly) Copyright !" # $%&'"' (($') %*&'

functionality into namespaces brings some order to your one global ob:ect and allows team members to understand where new functionality belongs as well as where to look for existing funtionality. -se the namespace function in -tils.:s to create a namespace. Event handling It,s always best to separate application logic from the event handler because the same logic may need to be triggered by different actions in the future. 2he eventhandler should be the only ob:ect that touches the event ob:ect. Application logic should never rely on the eetn ob:ect to function properly for the following reasons: 2he method interface makes it unclear what pieces of data are actually necessary. @ood A3Is are transparent in their expectations and dependencies) passing the event ob:ect as an argument does not give you any idea what it,s doing with which pieces of data. Because of that you need to recreate an event ob:ect in order to test the method. %xample: var .yApplication & 6 handle$lick : function4event56 event.prevent<efault45) this.show3opup4event.client/ event.clientA5) 7 show3opup: function4x y56 var popup & document.get%lementById4*popup,5) popup.style.left & x B *px,) popup.style.top & y B *px,) popup.class#ame & *reveal,) 7 7 addListener4element *click, function4event56 .yApplication.handle$lick4event5) 7 Avoid null comparisons
Source: Maintainable JavaScript by Nicholas Zakas (OReilly) Copyright !" # $%&'"' (($') %*&'

<etecting primitive values: 2here are five primitive values in +ava8cript: string number boolean null and undefined. 2esting for the type should be done with the typeof operator. Although using typeof like *typeof4variable5, is valid syntax this patterns makes typeof appear to be a function instead of an operator. >or this reason the pattern without parentheses is recommended. *typeof variable,. <etecting reference values: Ceference values are also known as ob:ects. In +ava8cript any value that is not a primitive is a reference. 2he typeof operator is of little use for reference values because it return s *ob:ect , for any type of ob:ect. 2he instanceof operator is the best way to detect values of a particular reference type. <etecting functions: -sing the typeof operator is the best way to detect functions. %xample: function my>unc4567 console.log4typeof my>unc &&& *function,5 DD true <etecting arrays: <etecting arrays should be done with the Array.isArray45 function. <etecting ob:ect properties: 2he best way to detect the presence of a property is to use the *in, operator 2he in operator simply checks for the presence of the named property without reading its value. %xample: var ob:ect & 6 count: ( related: null 7) if 4*count, in obe:ct5 6 DD this executes 7 hro! your o!n errors
Source: Maintainable JavaScript by Nicholas Zakas (OReilly) Copyright !" # $%&'"' (($') %*&'

2he problem with errors is that they tend to pop up in unexpected places and at unexpected times. 2o make matters worse the default +ava8cript error messages are notoriously uninformative ad cryptic which only compounds the problem. Imagine if an error popped up with a message that said: E2his function failed because this happenedF. Instantly your debugging task becomes easier. 2his ease is the advantage of throwing errors. It helps to think of errors as built!in failure cases. Its,s always easier to plan for a failure at a particular point in code than it is to anticipate failure everywhere. 2his is a very common practice in product design not :ust in code. Always include the function name in the error. "on#t modify ob$ects you don#t o!n %nterprise software needs a consisten and dependable execution environment to be maintainable. <o not override methods add new methods remove existing methods on ob:ects you don,t own.

Source: Maintainable JavaScript by Nicholas Zakas (OReilly) Copyright !" # $%&'"' (($') %*&'

Potrebbero piacerti anche