SlideShare a Scribd company logo
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 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
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?
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
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
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 ???
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
Pervasive Scope
     var x= 9;
     function foo() {
     alert(x);
     var x = 10;
     alert(x);
     };
     foo();

   Result : ???
Pervasive Scope
          var x= 9;
          function foo() {
          alert(x);
          var x = 10;
          alert(x);
          };
          foo();
   Result: undefined; 10;
   Expected: 9; 10;
Detect Features, Not Browser

if (document.getElementById)
{
    var element =
         document.getElementById ('MyId');
}
else
{
     alert(“ Your Browser lacks the capabilities
           required to run this script !”);
}
Test For an Element's Existence


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

{

       // code that works with innerHTML

}
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
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
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
Release Objects When Done

   Ex. Initialization Function

    var foo = function()
    {
    // code that makes this function work
    delete foo;
    }
    window.addEventListener('load', foo, false);
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!
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
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>
Use Object Oriented JavaScript

   Better reusability and organization
   Allows for dynamic loading of objects
   Write in a style more familiar to Java
    programmers
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;
}
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.
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);
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
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();
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
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
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
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
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
OpenSocial

   Common social networking API
   Write apps that work with any OpenSocial
    enable website
   Develop OpenSocial apps using only
    JavaScript, HTML, and CSS
Zembly

   Build widgets, applications with JavaScript,
    HTML and CSS
   OpenSocial soon!
   Now publicly available, go try it out, win a
    prize!
Agenda

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

   Take time to learn JavaScript and use best
    practices
   Prototype-based object system with object()
   Learn from the masters
   Let NetBeans help you!

More Related Content

What's hot

The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
Sasidhar Kothuru
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
kaven yan
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
Simon Willison
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
manugoel2003
 
ActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in JavaActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in Java
ipolevoy
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Zeeshan Khan
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
Retrofitting
RetrofittingRetrofitting
Retrofitting
Ted Husted
 
JavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderJavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilder
Andres Almiray
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
Andrew Alpert
 
Ajax Under The Hood
Ajax Under The HoodAjax Under The Hood
Ajax Under The Hood
WO Community
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript

What's hot (19)

The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
ActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in JavaActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in Java
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Retrofitting
RetrofittingRetrofitting
Retrofitting
 
JavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderJavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilder
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
 
Ajax Under The Hood
Ajax Under The HoodAjax Under The Hood
Ajax Under The Hood
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 

Similar to JavaScript Misunderstood

"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
Radoslav Georgiev
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
Pascal Rettig
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
jQuery for web development
jQuery for web developmentjQuery for web development
jQuery for web development
iFour Institute - Sustainable Learning
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
Thinqloud
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 

Similar to JavaScript Misunderstood (20)

"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
J Query
J QueryJ Query
J Query
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
jQuery for web development
jQuery for web developmentjQuery for web development
jQuery for web development
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 

More from Bhavya Siddappa

Huawei Club - Community Activity & Student Program
Huawei Club - Community Activity & Student ProgramHuawei Club - Community Activity & Student Program
Huawei Club - Community Activity & Student Program
Bhavya Siddappa
 
Android Introduction 2013
Android Introduction 2013Android Introduction 2013
Android Introduction 2013
Bhavya Siddappa
 
Women in Technology
Women in TechnologyWomen in Technology
Women in Technology
Bhavya Siddappa
 
Mobile Cloud Computing 2012
Mobile Cloud Computing 2012 Mobile Cloud Computing 2012
Mobile Cloud Computing 2012 Bhavya Siddappa
 
Graphology: Art of knowing a character
Graphology: Art of knowing a characterGraphology: Art of knowing a character
Graphology: Art of knowing a characterBhavya Siddappa
 
GTUG Intro
GTUG IntroGTUG Intro
GTUG Intro
Bhavya Siddappa
 
Windows Phone 7 Architecture Overview
Windows Phone 7 Architecture OverviewWindows Phone 7 Architecture Overview
Windows Phone 7 Architecture OverviewBhavya Siddappa
 
Mobile World Congress 2011 Overview
Mobile World Congress 2011 OverviewMobile World Congress 2011 Overview
Mobile World Congress 2011 OverviewBhavya Siddappa
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
Bhavya Siddappa
 
Android Anatomy
Android  AnatomyAndroid  Anatomy
Android Anatomy
Bhavya Siddappa
 
8 C's of Mobile EcoSystem
8 C's of Mobile EcoSystem8 C's of Mobile EcoSystem
8 C's of Mobile EcoSystem
Bhavya Siddappa
 
Google Io Introduction To Android
Google Io Introduction To AndroidGoogle Io Introduction To Android
Google Io Introduction To Android
Bhavya Siddappa
 
Apache Velocity
Apache VelocityApache Velocity
Apache Velocity
Bhavya Siddappa
 
Idea Camp Knowledge Is Power
Idea Camp  Knowledge Is PowerIdea Camp  Knowledge Is Power
Idea Camp Knowledge Is Power
Bhavya Siddappa
 
Idea Camp Idea Framework
Idea Camp  Idea FrameworkIdea Camp  Idea Framework
Idea Camp Idea Framework
Bhavya Siddappa
 
Secure Software
Secure SoftwareSecure Software
Secure Software
Bhavya Siddappa
 

More from Bhavya Siddappa (18)

Huawei Club - Community Activity & Student Program
Huawei Club - Community Activity & Student ProgramHuawei Club - Community Activity & Student Program
Huawei Club - Community Activity & Student Program
 
Android Introduction 2013
Android Introduction 2013Android Introduction 2013
Android Introduction 2013
 
Women in Technology
Women in TechnologyWomen in Technology
Women in Technology
 
Mobile Cloud Computing 2012
Mobile Cloud Computing 2012 Mobile Cloud Computing 2012
Mobile Cloud Computing 2012
 
Graphology: Art of knowing a character
Graphology: Art of knowing a characterGraphology: Art of knowing a character
Graphology: Art of knowing a character
 
GTUG Intro
GTUG IntroGTUG Intro
GTUG Intro
 
Windows Phone 7 Architecture Overview
Windows Phone 7 Architecture OverviewWindows Phone 7 Architecture Overview
Windows Phone 7 Architecture Overview
 
Mobile World Congress 2011 Overview
Mobile World Congress 2011 OverviewMobile World Congress 2011 Overview
Mobile World Congress 2011 Overview
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
 
Android Anatomy
Android  AnatomyAndroid  Anatomy
Android Anatomy
 
8 C's of Mobile EcoSystem
8 C's of Mobile EcoSystem8 C's of Mobile EcoSystem
8 C's of Mobile EcoSystem
 
Google Io Introduction To Android
Google Io Introduction To AndroidGoogle Io Introduction To Android
Google Io Introduction To Android
 
Apache Velocity
Apache VelocityApache Velocity
Apache Velocity
 
Idea Camp Knowledge Is Power
Idea Camp  Knowledge Is PowerIdea Camp  Knowledge Is Power
Idea Camp Knowledge Is Power
 
Idea Camp Idea Framework
Idea Camp  Idea FrameworkIdea Camp  Idea Framework
Idea Camp Idea Framework
 
Secure Software
Secure SoftwareSecure Software
Secure Software
 
WLST
WLSTWLST
WLST
 
eLearning 2.0
eLearning 2.0eLearning 2.0
eLearning 2.0
 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 

JavaScript Misunderstood

  • 1. JavaScript : Misunderstood Bhavya Siddappa www.bhavyavoice.blogspot.com
  • 2. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 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. 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. 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. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 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. 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. Pervasive Scope var x= 9; function foo() { alert(x); var x = 10; alert(x); }; foo();  Result : ???
  • 10. Pervasive Scope var x= 9; function foo() { alert(x); var x = 10; alert(x); }; foo();  Result: undefined; 10;  Expected: 9; 10;
  • 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. Test For an Element's Existence if ("innerHTML" in document.getElementById("someDiv")) { // code that works with innerHTML }
  • 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. 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. 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. Release Objects When Done  Ex. Initialization Function var foo = function() { // code that makes this function work delete foo; } window.addEventListener('load', foo, false);
  • 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. 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. 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. Use Object Oriented JavaScript  Better reusability and organization  Allows for dynamic loading of objects  Write in a style more familiar to Java programmers
  • 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. 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. 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. 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. 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. 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. 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. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 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. 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. OpenSocial  Common social networking API  Write apps that work with any OpenSocial enable website  Develop OpenSocial apps using only JavaScript, HTML, and CSS
  • 32. Zembly  Build widgets, applications with JavaScript, HTML and CSS  OpenSocial soon!  Now publicly available, go try it out, win a prize!
  • 33. Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 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!