JavaScript : Misunderstood



                        Bhavya Siddappa
            www.bhavyavoice.blogspot.com
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
The world’s most misunderstood
language
   The name
       it is originally called LiveScript
       JavaScript is not ...
JavaScript bad parts
   Design errors
       overloading of +, clobbered global variables,
        semicolon insertion.....
JavaScript Good parts
   Most used scripting language
     Every browser, many OSes(Windows, Dashboard), XUL(Mozilla),

...
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
Always use 'var'
   Keep your scopes straight with var keyword
       Global scope
       Function scope
            va...
Always use 'var'

   Keep your scopes straight with var keyword
       Global scope
       Function scope

            ...
Pervasive Scope
     var x= 9;
     function foo() {
     alert(x);
     var x = 10;
     alert(x);
     };
     foo();

...
Pervasive Scope
          var x= 9;
          function foo() {
          alert(x);
          var x = 10;
          alert(x...
Detect Features, Not Browser

if (document.getElementById)
{
    var element =
         document.getElementById ('MyId');
...
Test For an Element's Existence


if ("innerHTML" in document.getElementById("someDiv"))

{

       // code that works wit...
Don't Make Assumptions

   NEVER rely on JavaScript
   Don't expect JavaScript to be available but
    make it a nice-to...
Don't use with()
with (document.forms["mainForm"].elements)

{                                                      Bad
i...
Eval is Evil

   Most powerful and possibly most misused
    method in JavaScript
   Like...
    “swatting a fly with a ...
Release Objects When Done

   Ex. Initialization Function

    var foo = function()
    {
    // code that makes this fun...
Square Bracket Notation
   Dot notation: MyObject.property
   Bracket notation: MyObject[“property”]
    MyObject[“value...
Unobtrusive JavaScript

   We separate Presentation (CSS) from Content
    (XHTML)
   We separate Behavior (JS) from Con...
Unobtrusive JavaScript
   Bad
<a href="JavaScript:alert('You clicked!')">Click Me!</a>
<a href="#" onclick="alert('You cl...
Use Object Oriented JavaScript

   Better reusability and organization
   Allows for dynamic loading of objects
   Writ...
Object Oriented Example
function Cart() {
this.items = [];
}
function Item (id,name,desc,price) {
this.id = id;
this.name ...
Use Object Hierarchies

   In JavaScript names may collide
       In Java we have packages to prevent this
   JavaScrip...
Object Hierarchies Example
// create the base BLUEPRINTS object if it does not exist.
if (!BLUEPRINTS) {
var BLUEPRINTS = ...
Use the Prototype Property

   Use to define shared behavior and to extend
    objects
   The prototype property is a fe...
Prototype Property Example
function Cart() {
this.items = [ ];
}
function Item (id,name,desc,price)) {
this.id = id;
this....
Object Literals

   Object literals are objects defined using
    braces that contain a set of comma separated
    key/va...
Reduce the Size of JavaScript File
   Remove the whitespace and shorten the
    name of variables and functions in a file...
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
JSON

   Becoming de-facto standard in transferring
    information for AJAX applications
   Allows us to make cross-dom...
Getters and Setters in JavaScript 1.5
Technology
   Define functions to be invoked when a
    property is accessed
   Tr...
OpenSocial

   Common social networking API
   Write apps that work with any OpenSocial
    enable website
   Develop O...
Zembly

   Build widgets, applications with JavaScript,
    HTML and CSS
   OpenSocial soon!
   Now publicly available,...
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
Conclusions

   Take time to learn JavaScript and use best
    practices
   Prototype-based object system with object()
...
Upcoming SlideShare
Loading in …5
×

JavaScript Misunderstood

3,065 views

Published on

Why JavaScript is the most Misunderstood Language and some of its Best practices.

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,065
On SlideShare
0
From Embeds
0
Number of Embeds
71
Actions
Shares
0
Downloads
35
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

JavaScript Misunderstood

  1. 1. JavaScript : Misunderstood Bhavya Siddappa www.bhavyavoice.blogspot.com
  2. 2. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  3. 3. The world’s most misunderstood language  The name  it is originally called LiveScript  JavaScript is not a subset of Java nor interpreted version of Java  Too many versions  ECMA committee  Bad official specification  Bad reputation – broken language?  Lousy implementation: Browsers do suck Implementations of CSS, events, ... broken Language itself is pretty reliable  Blame IE
  4. 4. JavaScript bad parts  Design errors  overloading of +, clobbered global variables, semicolon insertion...  24.88 + 4.35 -> 29.229999999999997  0 0.0 ”0” “0.0” null undefined are all false  0.0 + ”0” -> ”00”  No class public private keywords  No package keyword either  How does this work anyway?
  5. 5. JavaScript Good parts  Most used scripting language  Every browser, many OSes(Windows, Dashboard), XUL(Mozilla), Flash(ActionScript), Server-side(Phobos, ASP, Rhino), ...  Great for UI-coding  Flexible and powerful  OO, functional  Closures + Anonymous functions  Everything is an object (including functions)  Prototype-based inheritance  AJAX makes it a must-know JavaScript can be used to do good stuff
  6. 6. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  7. 7. Always use 'var'  Keep your scopes straight with var keyword  Global scope  Function scope var i=0; // Global variable function test() { for (i=0; i<10; i++) { alert("Hello World!"); } } test(); alert(i); // i is ???
  8. 8. Always use 'var'  Keep your scopes straight with var keyword  Global scope  Function scope function test() { for (var i=0; i<10; i++) { alert("Hello World!"); } } // i is 10
  9. 9. Pervasive Scope var x= 9; function foo() { alert(x); var x = 10; alert(x); }; foo();  Result : ???
  10. 10. Pervasive Scope var x= 9; function foo() { alert(x); var x = 10; alert(x); }; foo();  Result: undefined; 10;  Expected: 9; 10;
  11. 11. Detect Features, Not Browser if (document.getElementById) { var element = document.getElementById ('MyId'); } else { alert(“ Your Browser lacks the capabilities required to run this script !”); }
  12. 12. Test For an Element's Existence if ("innerHTML" in document.getElementById("someDiv")) { // code that works with innerHTML }
  13. 13. Don't Make Assumptions  NEVER rely on JavaScript  Don't expect JavaScript to be available but make it a nice-to-have rather than a dependency  Expect other scripts to try to interfere with your functionality and keep the scope of your scripts as secure as possible.  Ex. JavaScript is enabled but is blocked by a firewall or security policy
  14. 14. Don't use with() with (document.forms["mainForm"].elements) {  Bad input1.value = "junk"; input2.value = "junk"; } var elements = document.forms["mainForm"].elements; elements.input1.value = "junk"; elements.input2.value = "junk";  Good
  15. 15. Eval is Evil  Most powerful and possibly most misused method in JavaScript  Like... “swatting a fly with a sledgehammer”  Every time eval() called, compilation occurs  When is it ok? Math expressions, serialization, dynamic loading of code
  16. 16. Release Objects When Done  Ex. Initialization Function var foo = function() { // code that makes this function work delete foo; } window.addEventListener('load', foo, false);
  17. 17. Square Bracket Notation  Dot notation: MyObject.property  Bracket notation: MyObject[“property”] MyObject[“value”+i] OK! MyObject.value+i Fail!  Forms document.forms["formname"].elements["inputname"] OK! document.formname.inputname Bad!
  18. 18. Unobtrusive JavaScript  We separate Presentation (CSS) from Content (XHTML)  We separate Behavior (JS) from Content  Place CSS and JavaScript in separate files  Dynamically add behavior instead of hard- coding
  19. 19. Unobtrusive JavaScript  Bad <a href="JavaScript:alert('You clicked!')">Click Me!</a> <a href="#" onclick="alert('You clicked!')">Click Me!</a>  OK <a href="clicked.html" onclick="alert('You clicked!')"> Click Me </a>  Good var div = document.getElementById('clickMe'); div.onclick = new Function("processClick(this)"); <a id=”clickMe” href=”clicked.html”>Click Me!</a>
  20. 20. Use Object Oriented JavaScript  Better reusability and organization  Allows for dynamic loading of objects  Write in a style more familiar to Java programmers
  21. 21. Object Oriented Example function Cart() { this.items = []; } function Item (id,name,desc,price) { this.id = id; this.name = name; this.desc = desc; this.price = price; } var cart = new Cart(); cart.items.push(new Item("id-1","Paper","something you write on",5)); cart.items.push(new Item("id-2","Pen", "Something you write with",3)); var total = 0; for (var l == 0; l < cart.items.length; l++ ) { total = total + cart.items[l].price; }
  22. 22. Use Object Hierarchies  In JavaScript names may collide  In Java we have packages to prevent this  JavaScript does not have packages  You can use JavaScript objects to organize related objects and prevent naming collisions.
  23. 23. Object Hierarchies Example // create the base BLUEPRINTS object if it does not exist. if (!BLUEPRINTS) { var BLUEPRINTS = new Object(); } // define Cart under BLUEPRINTS BLUEPRINTS.Cart = function () { this.items = []; this.addItem = function(id, qty) { this.items.push(new Item(id, qty)); } function Item (id, qty) { this.id = id; this.qty = qty; } } // create an instance of the cart and add an item var cart = new BLUEPRINTS.Cart(); cart.addItem("id-1", 5); cart.addItem("id-2", 10);
  24. 24. Use the Prototype Property  Use to define shared behavior and to extend objects  The prototype property is a feature of the  JavaScript language  The property is available on all objects
  25. 25. Prototype Property Example function Cart() { this.items = [ ]; } function Item (id,name,desc,price)) { this.id = id; this.name = name; this.desc = desc; this.price = price; } //SmartCart extends the Cart object inheriting its properties and adds a total property Function SmartCart() { this.total = 0; } SmartCart.prototype = new Cart();
  26. 26. Object Literals  Object literals are objects defined using braces that contain a set of comma separated key/value pairs, similar to a map in Java  Example  {key1: “stringValue”, key2: 2, key3: ['blue', 'yellow']  Object literals can be used as parameters  Don't confuse them with JSON, which has a similar syntax
  27. 27. Reduce the Size of JavaScript File  Remove the whitespace and shorten the name of variables and functions in a file  While developing, don't compress so that debugging is easier  When ready to deploy, consider compressing your JavaScript files  Use minimized (compressed) versions of 3rd party libraries when available  Example tool for compression: ShrinkSafe
  28. 28. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  29. 29. JSON  Becoming de-facto standard in transferring information for AJAX applications  Allows us to make cross-domain requests if server supports it  Perfect for serializing JavaScript objects
  30. 30. Getters and Setters in JavaScript 1.5 Technology  Define functions to be invoked when a property is accessed  Transparent to the client var squareProto = { side: 0, get area() { return this.side * this.side; } }; var mySquare = object(squareProto); mySquare.side = 5; ⊳ mySquare.area - > 25
  31. 31. OpenSocial  Common social networking API  Write apps that work with any OpenSocial enable website  Develop OpenSocial apps using only JavaScript, HTML, and CSS
  32. 32. Zembly  Build widgets, applications with JavaScript, HTML and CSS  OpenSocial soon!  Now publicly available, go try it out, win a prize!
  33. 33. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  34. 34. Conclusions  Take time to learn JavaScript and use best practices  Prototype-based object system with object()  Learn from the masters  Let NetBeans help you!

×