Javascript Best Practices

## Javascript Best Practices

# Spaces around operators
Good:
5 + 4
Bad:
5+4

# Space after every comma
Good: 5, 6, 7
Bad: 5,6,7

# One statement per line
Good:
a+3
b+4
Bad:
a+3;b+4

# Always use braces for blocks
Good:
if a {
stuff;
}
Bad: if a
stuff();

# Use {‘s at the end of a line
Good:
if a {
Bad:
if a
{

# Use line comments within code
Good:
// these are
// comments
Bad:
/* these
are comments */

# Declare variables at the start of functions (function scope)
Good:
var x = 0;

x+=1
Bad:

x+=1

# For comparisons use === or !==(objects, same type, preferred use) or use == or !=(values, type doesn’t matter) instead of =
Good:
if a === b

if adr1 == adr2

Bad:
if a = b

if adr1 = adr2
..

# Always break out of of switch case statements
Good:
switch(expression) {
case n:
code block
break;
case n:
code block
break;

Bad:
switch(expression) {
case n:
code block
case n:
code block

Use a global variables to namespace an application

Good:
MyAmazoApp.recently_viewed = 1
Bad:
recently_viewed = 1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s