SlideShare a Scribd company logo
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	
  
JavaScript Good Practices
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/	
  	
  
JavaScript Good Practices
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	
  
JavaScript Good Practices
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);
JavaScript Good Practices
JavaScript Good Practices
JavaScript Good Practices
JavaScript Good Practices
Prin+ng	
  to	
  Console	
  
•  Debugging	
  in	
  Browsers:	
  use	
  console	
  –	
  object	
  
•  Firefox	
  
    –  Firebug	
  extension	
  
•  Safari	
  
    –  Enable	
  developer	
  mode	
  
•  How?	
  
    –  console.log(“Hello	
  World!”);	
  
JavaScript Good Practices
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

More Related Content

What's hot (20)

PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PPTX
Introduction To JavaScript
Reema
 
PDF
Introduction to Javascript programming
Fulvio Corno
 
PPT
Java script
vishal choudhary
 
PPTX
Node.js System: The Approach
Haci Murat Yaman
 
PPTX
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
PPT
Web development basics (Part-4)
Rajat Pratap Singh
 
PPTX
Javascript basics for automation testing
Vikas Thange
 
PPTX
Introduction to Javascript By Satyen
Satyen Pandya
 
PDF
Performance Optimization and JavaScript Best Practices
Doris Chen
 
PDF
JavaScript
Ivano Malavolta
 
PDF
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
PPTX
JS - Basics
John Fischer
 
PPTX
Javascript
Nagarajan
 
PPT
Learn javascript easy steps
prince Loffar
 
PPTX
An Introduction to JavaScript
tonyh1
 
PDF
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
ODP
Object Oriented Javascript
NexThoughts Technologies
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Introduction To JavaScript
Reema
 
Introduction to Javascript programming
Fulvio Corno
 
Java script
vishal choudhary
 
Node.js System: The Approach
Haci Murat Yaman
 
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
Web development basics (Part-4)
Rajat Pratap Singh
 
Javascript basics for automation testing
Vikas Thange
 
Introduction to Javascript By Satyen
Satyen Pandya
 
Performance Optimization and JavaScript Best Practices
Doris Chen
 
JavaScript
Ivano Malavolta
 
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
JS - Basics
John Fischer
 
Javascript
Nagarajan
 
Learn javascript easy steps
prince Loffar
 
An Introduction to JavaScript
tonyh1
 
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
Object Oriented Javascript
NexThoughts Technologies
 

Viewers also liked (7)

PDF
Intro to PhoneGap
Jussi Pohjolainen
 
PDF
Intro to Java ME and Asha Platform
Jussi Pohjolainen
 
PDF
Intro to HTML5
Jussi Pohjolainen
 
PDF
Introduction to Java ME
Jussi Pohjolainen
 
PDF
Intro to JavaScript
Jussi Pohjolainen
 
PPTX
PHP tutorial | ptutorial
PTutorial Web
 
PDF
Java JDBC
Jussi Pohjolainen
 
Intro to PhoneGap
Jussi Pohjolainen
 
Intro to Java ME and Asha Platform
Jussi Pohjolainen
 
Intro to HTML5
Jussi Pohjolainen
 
Introduction to Java ME
Jussi Pohjolainen
 
Intro to JavaScript
Jussi Pohjolainen
 
PHP tutorial | ptutorial
PTutorial Web
 
Ad

Similar to JavaScript Good Practices (20)

KEY
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
PDF
l2-es6-160830040119.pdf
Hương Trà Pé Xjnk
 
PPT
introduction to javascript concepts .ppt
ansariparveen06
 
PDF
Lecture 2: ES6 / ES2015 Slide
Kobkrit Viriyayudhakorn
 
PDF
Advanced JavaScript Development
Jussi Pohjolainen
 
PPT
fundamentals of JavaScript for students.ppt
dejen6
 
PPT
Basics of Javascript
Universe41
 
PPT
Javascript
Sunil Thakur
 
PDF
Basics of JavaScript
Bala Narayanan
 
PPT
Java Script
Sarvan15
 
PDF
Java Script
Sarvan15
 
PPTX
JavaScript_III.pptx
rashmiisrani1
 
PPT
Presentation JavaScript Introduction Data Types Variables Control Structure
SripathiRavi1
 
PPT
JavaScript ppt for introduction of javascripta
nehatanveer5765
 
PPTX
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
PPTX
JavaScript Basics - GameCraft Training
Radoslav Georgiev
 
PPT
13665449.ppt
JP Chicano
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PPTX
Javascript fundamentals and not
Salvatore Fazio
 
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
l2-es6-160830040119.pdf
Hương Trà Pé Xjnk
 
introduction to javascript concepts .ppt
ansariparveen06
 
Lecture 2: ES6 / ES2015 Slide
Kobkrit Viriyayudhakorn
 
Advanced JavaScript Development
Jussi Pohjolainen
 
fundamentals of JavaScript for students.ppt
dejen6
 
Basics of Javascript
Universe41
 
Javascript
Sunil Thakur
 
Basics of JavaScript
Bala Narayanan
 
Java Script
Sarvan15
 
Java Script
Sarvan15
 
JavaScript_III.pptx
rashmiisrani1
 
Presentation JavaScript Introduction Data Types Variables Control Structure
SripathiRavi1
 
JavaScript ppt for introduction of javascripta
nehatanveer5765
 
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
JavaScript Basics - GameCraft Training
Radoslav Georgiev
 
13665449.ppt
JP Chicano
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Javascript fundamentals and not
Salvatore Fazio
 
Ad

More from Jussi Pohjolainen (20)

PDF
Moved to Speakerdeck
Jussi Pohjolainen
 
PDF
Java Web Services
Jussi Pohjolainen
 
PDF
Box2D and libGDX
Jussi Pohjolainen
 
PDF
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
PDF
libGDX: Tiled Maps
Jussi Pohjolainen
 
PDF
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 
PDF
Intro to Building Android Games using libGDX
Jussi Pohjolainen
 
PDF
Introduction to JavaScript
Jussi Pohjolainen
 
PDF
Introduction to AngularJS
Jussi Pohjolainen
 
PDF
libGDX: Scene2D
Jussi Pohjolainen
 
PDF
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
PDF
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
PDF
libGDX: User Input
Jussi Pohjolainen
 
PDF
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
PDF
Building Android games using LibGDX
Jussi Pohjolainen
 
PDF
Android Threading
Jussi Pohjolainen
 
PDF
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
PDF
Creating Games for Asha - platform
Jussi Pohjolainen
 
PDF
Intro to Asha UI
Jussi Pohjolainen
 
PDF
Quick Intro to JQuery and JQuery Mobile
Jussi Pohjolainen
 
Moved to Speakerdeck
Jussi Pohjolainen
 
Java Web Services
Jussi Pohjolainen
 
Box2D and libGDX
Jussi Pohjolainen
 
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
libGDX: Tiled Maps
Jussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 
Intro to Building Android Games using libGDX
Jussi Pohjolainen
 
Introduction to JavaScript
Jussi Pohjolainen
 
Introduction to AngularJS
Jussi Pohjolainen
 
libGDX: Scene2D
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: User Input
Jussi Pohjolainen
 
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Building Android games using LibGDX
Jussi Pohjolainen
 
Android Threading
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Jussi Pohjolainen
 
Intro to Asha UI
Jussi Pohjolainen
 
Quick Intro to JQuery and JQuery Mobile
Jussi Pohjolainen
 

Recently uploaded (20)

PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 

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);  
  • 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   function something() { // window object now has variable property! variable = "hi there!"; } something(); // prints "hi there!" console.log(variable);
  • 24. Problem  2   function something() { // 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   function test() { var a = 1, b = 2,…; } test();
  • 31. For  loops   for(var i = 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