KEMBAR78
JavaScript Good Practices | PDF
JS	
  Good	
  Prac+ses	
  

            Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
JS	
  and	
  OO	
  
•  Javascript	
  is	
  an	
  object-­‐oriented	
  language!	
  
•  Only	
  five	
  primi+ve	
  types:	
  number,	
  string,	
  
   boolean,	
  null,	
  undefined	
  
    –  Object	
  wrappers	
  for	
  number,	
  string	
  and	
  boolean	
  
       available	
  
•  Object	
  is	
  just	
  a	
  collec+on	
  of	
  named	
  proper+es,	
  
   a	
  list	
  of	
  key-­‐value	
  pairs	
  
    –  Some	
  of	
  the	
  proper+es	
  can	
  be	
  func+ons!	
  
•  No	
  classes!	
  
Object	
  types	
  
•  Na+ve	
  (Core	
  Javascript)	
  
       –  ECMAScript	
  standard:	
  Array,	
  Date..	
  
•  Host 	
  	
  
       –  The	
  host	
  environment,	
  for	
  example	
  browser:	
  
          window,	
  DOM	
  objects	
  
	
  
EcmaScript	
  
•  The	
  core	
  JS	
  programming	
  language	
  
    –  Does	
  not	
  include	
  DOM,	
  BOM	
  
•  Version	
  5:	
  Strict	
  mode	
  
    –  Removes	
  features	
  from	
  the	
  language!	
  Raises	
  
       errors	
  that	
  were	
  okay	
  in	
  non	
  strict	
  mode	
  
    –  Backward	
  compa+ble	
  
    –  Add	
  “use	
  strict”,	
  in	
  func+on	
  or	
  global	
  scope	
  
•  In	
  future	
  strict	
  mode	
  is	
  the	
  one	
  to	
  go…	
  
Rhino	
  (JavaScript	
  Engine)	
  
•  Open	
  Source	
  JS	
  Engine	
  developed	
  in	
  Java	
  
    –  Mozilla	
  Founda+on	
  
•  No	
  built	
  in	
  support	
  for	
  web	
  browser	
  objects	
  
•  Has	
  Rhino	
  shell	
  for	
  running	
  JS	
  in	
  command	
  line	
  
•  Is	
  bundled	
  in	
  Java	
  SE	
  6	
  
Any	
  problems	
  in	
  the	
  code?	
  
function sum (a, b)
{
    s = a + b;
    return s;
}

x = sum(5,5);

// Rhino's way to print to console
print (x);
JSLint	
  
•  JSLint	
  is	
  JS	
  code	
  quality	
  tool	
  
     –  h_p://jslint.com	
  
•  Inspects	
  and	
  warns	
  about	
  poten+al	
  problems	
  
•  “Will	
  hurt	
  your	
  feelings”	
  
•  Excepts	
  that	
  your	
  code	
  is	
  in	
  “strict	
  mode”	
  
•  Can	
  be	
  used	
  via	
  website	
  or	
  command	
  line	
  
   (installa+on	
  required)	
  
•  Command	
  line	
  tool	
  (Java	
  wrapper	
  for	
  JSLint)	
  
     –  h_p://code.google.com/p/jslint4java/	
  	
  
JSLint	
  in	
  Command	
  Line	
  
•  JSLint4java	
  –	
  Java	
  wrapper	
  for	
  the	
  JSLint	
  
     –  h_p://code.google.com/p/jslint4java/	
  
•  To	
  use	
  it:	
  
     –  java	
  -­‐jar	
  jslint4java-­‐1.4.jar	
  applica+on.js	
  
Aeer	
  some	
  modifica+ons	
  
function sum(a, b) {
    "use strict";

    var s = a + b;
    return s;
}

var x = sum(5, 5);

// Rhino's way to print to console
print(x);
Prin+ng	
  to	
  Console	
  
•  Debugging	
  in	
  Browsers:	
  use	
  console	
  –	
  object	
  
•  Firefox	
  
    –  Firebug	
  extension	
  
•  Safari	
  
    –  Enable	
  developer	
  mode	
  
•  How?	
  
    –  console.log(“Hello	
  World!”);	
  
Global	
  Variables	
  
•  Every	
  JS	
  environment	
  has	
  a	
  global	
  object	
  
•  Every	
  global	
  variable	
  becomes	
  a	
  property	
  of	
  
   the	
  global	
  object	
  
       –  In	
  browser	
  environment:	
  window	
  is	
  the	
  global	
  
          object	
  itself	
  
	
  
Declaring	
  Global	
  variable	
  
//	
  global	
  object,	
  window,	
  will	
  get	
  a	
  new	
  property!	
  
variable	
  =	
  "hi	
  there!";	
  
	
  
console.log(variable);	
  
	
  
//	
  And	
  different	
  ways	
  to	
  access	
  the	
  variable	
  
console.log(window.variable);	
  
console.log(window.variable);	
  
console.log(window["variable"]);	
  
console.log(this.variable);	
  
	
  
console.log(window);	
  
Window	
  proper+es	
  
Problems	
  
•  Global	
  variables	
  shared	
  among	
  all	
  the	
  code	
  
•  What	
  if	
  you	
  use	
  some	
  third	
  party	
  JavaScript	
  
   Library	
  like	
  JQuery	
  or	
  Modernizr?	
  Name	
  
   collision!	
  
•  Avoid	
  Globals!	
  
Problem	
  1	
  
function something() {
    // window object now has variable property!
    variable = "hi there!";
}

something();

// prints "hi there!"
console.log(variable);
Problem	
  2	
  
function something() {
    // window object now has z property!
    var x = z = "hello";
}

something();

// prints "hello"
console.log(z);
Difference	
  when	
  using	
  var	
  
var x = 20;
y = 21;

console.log(window.x);   // 20
console.log(window.y);   // 21

delete x; // does not delete anything
delete y; // removes the y from window

console.log(window.x);   // 20
console.log(window.y);   // undefined
Using	
  var	
  
•  Use	
  always	
  var!	
  
•  In	
  strict	
  mode,	
  assignments	
  to	
  undeclared	
  
   variables	
  will	
  throw	
  an	
  error!	
  
Func+ons	
  and	
  Variable	
  Declaring	
  
var x = 10;

function test() {

     console.log(x);   // outputs what?

     if(true) {
         var x = 5;
     }
}

test();
What	
  really	
  happens	
  
var x = 10;

function test() {
    var x;
    console.log(x);   // outputs “undefined”

    if(true) {
        x = 5;
    }
}

test();
Variable	
  Hois+ng	
  
•  When	
  you	
  declare	
  a	
  variable	
  inside	
  a	
  func+on,	
  
   it	
  acts	
  like	
  it	
  was	
  declared	
  at	
  the	
  top	
  of	
  the	
  
   func+on!	
  
•  Declare	
  always	
  your	
  variables	
  at	
  the	
  top!	
  
Like	
  this	
  
function test() {
    var a = 1, b = 2,…;

}

test();
For	
  loops	
  
for(var i = 0; i < somearray.length; i++)
{
   doSomething();
}
ó
var max = somearray.length;
for(var i = 0; i < max; i++) {
    doSomething()
}
Comparison	
  
false == 0 => true
“” == 0    => true
Use
false === 0 => false
“” === 0    => false
eval()	
  
•  eval()	
  func+on	
  takes	
  JS	
  (string)	
  and	
  executes	
  
   it.	
  
•  Security	
  issues:	
  don’t	
  use	
  it!	
  
•  To	
  parse	
  JSON	
  objects,	
  use	
  JSON.parse();	
  
Code	
  Style	
  
•  Indenta+on:	
  4	
  spaces	
  (default	
  for	
  JSLint)	
  
•  Use	
  always	
  curly	
  braces	
  
•  Naming	
  conven+ons:	
  	
  
    –  Use	
  capital	
  le_er	
  in	
  constructor	
  func+ons:	
  	
  
    –  var	
  jack	
  =	
  new	
  Person();	
  
    	
  
    	
  
Documen+ng	
  your	
  code	
  
•  It’s	
  possible	
  to	
  generate	
  documenta+on	
  from	
  
   your	
  comments	
  (like	
  Javadoc	
  in	
  Java)	
  
•  Free	
  tools	
  like	
  
   –  JSDoc	
  toolkit	
  
        •  h_p://code.google.com/p/jsdoc-­‐toolkit/	
  
   –  YUIDoc	
  	
  
        •  h_p://yuilibrary.com/projects/yuidoc/	
  
Minimizing	
  your	
  code	
  
•  The	
  Closure	
  Compiler	
  is	
  a	
  tool	
  for	
  making	
  
   JavaScript	
  download	
  and	
  run	
  faster	
  
•  Google	
  Closure	
  Compiler	
  
    –  h_ps://developers.google.com/closure/compiler/	
  
•  Can	
  be	
  user	
  by	
  command	
  line	
  or	
  web	
  
    –  h_p://closure-­‐compiler.appspot.com/home	
  
JavaScript Good Practices

JavaScript Good Practices

  • 1.
    JS  Good  Prac+ses   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2.
    JS  and  OO   •  Javascript  is  an  object-­‐oriented  language!   •  Only  five  primi+ve  types:  number,  string,   boolean,  null,  undefined   –  Object  wrappers  for  number,  string  and  boolean   available   •  Object  is  just  a  collec+on  of  named  proper+es,   a  list  of  key-­‐value  pairs   –  Some  of  the  proper+es  can  be  func+ons!   •  No  classes!  
  • 3.
    Object  types   • Na+ve  (Core  Javascript)   –  ECMAScript  standard:  Array,  Date..   •  Host     –  The  host  environment,  for  example  browser:   window,  DOM  objects    
  • 4.
    EcmaScript   •  The  core  JS  programming  language   –  Does  not  include  DOM,  BOM   •  Version  5:  Strict  mode   –  Removes  features  from  the  language!  Raises   errors  that  were  okay  in  non  strict  mode   –  Backward  compa+ble   –  Add  “use  strict”,  in  func+on  or  global  scope   •  In  future  strict  mode  is  the  one  to  go…  
  • 5.
    Rhino  (JavaScript  Engine)   •  Open  Source  JS  Engine  developed  in  Java   –  Mozilla  Founda+on   •  No  built  in  support  for  web  browser  objects   •  Has  Rhino  shell  for  running  JS  in  command  line   •  Is  bundled  in  Java  SE  6  
  • 7.
    Any  problems  in  the  code?   function sum (a, b) { s = a + b; return s; } x = sum(5,5); // Rhino's way to print to console print (x);
  • 8.
    JSLint   •  JSLint  is  JS  code  quality  tool   –  h_p://jslint.com   •  Inspects  and  warns  about  poten+al  problems   •  “Will  hurt  your  feelings”   •  Excepts  that  your  code  is  in  “strict  mode”   •  Can  be  used  via  website  or  command  line   (installa+on  required)   •  Command  line  tool  (Java  wrapper  for  JSLint)   –  h_p://code.google.com/p/jslint4java/    
  • 10.
    JSLint  in  Command  Line   •  JSLint4java  –  Java  wrapper  for  the  JSLint   –  h_p://code.google.com/p/jslint4java/   •  To  use  it:   –  java  -­‐jar  jslint4java-­‐1.4.jar  applica+on.js  
  • 12.
    Aeer  some  modifica+ons   function sum(a, b) { "use strict"; var s = a + b; return s; } var x = sum(5, 5); // Rhino's way to print to console print(x);
  • 17.
    Prin+ng  to  Console   •  Debugging  in  Browsers:  use  console  –  object   •  Firefox   –  Firebug  extension   •  Safari   –  Enable  developer  mode   •  How?   –  console.log(“Hello  World!”);  
  • 19.
    Global  Variables   • Every  JS  environment  has  a  global  object   •  Every  global  variable  becomes  a  property  of   the  global  object   –  In  browser  environment:  window  is  the  global   object  itself    
  • 20.
    Declaring  Global  variable   //  global  object,  window,  will  get  a  new  property!   variable  =  "hi  there!";     console.log(variable);     //  And  different  ways  to  access  the  variable   console.log(window.variable);   console.log(window.variable);   console.log(window["variable"]);   console.log(this.variable);     console.log(window);  
  • 21.
  • 22.
    Problems   •  Global  variables  shared  among  all  the  code   •  What  if  you  use  some  third  party  JavaScript   Library  like  JQuery  or  Modernizr?  Name   collision!   •  Avoid  Globals!  
  • 23.
    Problem  1   functionsomething() { // window object now has variable property! variable = "hi there!"; } something(); // prints "hi there!" console.log(variable);
  • 24.
    Problem  2   functionsomething() { // window object now has z property! var x = z = "hello"; } something(); // prints "hello" console.log(z);
  • 25.
    Difference  when  using  var   var x = 20; y = 21; console.log(window.x); // 20 console.log(window.y); // 21 delete x; // does not delete anything delete y; // removes the y from window console.log(window.x); // 20 console.log(window.y); // undefined
  • 26.
    Using  var   • Use  always  var!   •  In  strict  mode,  assignments  to  undeclared   variables  will  throw  an  error!  
  • 27.
    Func+ons  and  Variable  Declaring   var x = 10; function test() { console.log(x); // outputs what? if(true) { var x = 5; } } test();
  • 28.
    What  really  happens   var x = 10; function test() { var x; console.log(x); // outputs “undefined” if(true) { x = 5; } } test();
  • 29.
    Variable  Hois+ng   • When  you  declare  a  variable  inside  a  func+on,   it  acts  like  it  was  declared  at  the  top  of  the   func+on!   •  Declare  always  your  variables  at  the  top!  
  • 30.
    Like  this   functiontest() { var a = 1, b = 2,…; } test();
  • 31.
    For  loops   for(vari = 0; i < somearray.length; i++) { doSomething(); } ó var max = somearray.length; for(var i = 0; i < max; i++) { doSomething() }
  • 32.
    Comparison   false ==0 => true “” == 0 => true Use false === 0 => false “” === 0 => false
  • 33.
    eval()   •  eval()  func+on  takes  JS  (string)  and  executes   it.   •  Security  issues:  don’t  use  it!   •  To  parse  JSON  objects,  use  JSON.parse();  
  • 34.
    Code  Style   • Indenta+on:  4  spaces  (default  for  JSLint)   •  Use  always  curly  braces   •  Naming  conven+ons:     –  Use  capital  le_er  in  constructor  func+ons:     –  var  jack  =  new  Person();      
  • 35.
    Documen+ng  your  code   •  It’s  possible  to  generate  documenta+on  from   your  comments  (like  Javadoc  in  Java)   •  Free  tools  like   –  JSDoc  toolkit   •  h_p://code.google.com/p/jsdoc-­‐toolkit/   –  YUIDoc     •  h_p://yuilibrary.com/projects/yuidoc/  
  • 36.
    Minimizing  your  code   •  The  Closure  Compiler  is  a  tool  for  making   JavaScript  download  and  run  faster   •  Google  Closure  Compiler   –  h_ps://developers.google.com/closure/compiler/   •  Can  be  user  by  command  line  or  web   –  h_p://closure-­‐compiler.appspot.com/home