SlideShare a Scribd company logo
JavaScript
Best Practices


Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com
Disclaimer & Acknowledgments
• Even though Sang Shin is a full-time employee of
  Sun Microsystems, the contents here are created as
  his own personal endeavor and thus does not
  necessarily reflect any official stance of Sun
  Microsystems on any particular technology
• Acknowledgments
  > The contents of this presentation was created from
    “JavaScript recommendations for AJAX component writers”
    written by Greg Murray
     > https://blueprints.dev.java.net/bpcatalog/conventions/javascript-
       recommendations.html

                                                                           2
Topics

•   Use Object-oriented JavaScript
•   Use Object hierarchy
•   Use the prototype property
•   Write reusable JavaScript code
•   Use Object literals as function parameters
•   Load JavaScript on demand
•   Clean separation of content, CSS, and JavaScript
•   Reduce the size of JavaScript file
                                                       3
Use Object Oriented
JavaScript
Use Object Oriented JavaScript

• Provides better reusability of the code
• Enables your objects to be better organized
• Allow for dynamic loading of objects




                                                5
Example: Cart Object in JavaScript
// The Cart object above provides basic support for maintaining
     //
// an internal array of Item objects
function Cart() {
  this.items = [];
}
function Item (id,name,desc,price) {
    this.id = id;
    this.name = name;
    this.desc = desc;
    this.price = price;
}
// Create an instance of the Cart and add items
var cart = new Cart();
cart.items.push(new Item(quot;id-1quot;,quot;Paperquot;,quot;something you write onquot;,5));
cart.items.push(new Item(quot;id-2quot;,quot;Penquot;, quot;Something you write withquot;,3));
var total = 0;
for (var l = 0; l < cart.items.length; l++) {
   total = total + cart.items[l].price;
}
                                                                         6
Example: Comparable Java Code
public class Cart {
  private ArrayList items = new ArrayList();
  public ArrayList getItems() {
     return items;
  }
}
public class Item {
  private String id; private String name; private String desc; private double price;
    public Item(String id, String name, String desc, double price) {
      this.id = id;
      this.name = name;
      this.desc = desc;
      this.price = price;
    }
    public String getId() {return id;}
    public String getName() {return name;}
    public String getDesc() {return desc;}
    public float getPrice() {return price;}
}
                                                                                       7
Use Object Hierarchy
Use Object Hierarchies to Organize
JavaScript Objects to Avoid Name Collision

• In JavaScript there is the potential for object names
  to collide
  > In Java language, package names are used to prevent
    naming collisions
• JavaScript does not provide package names like
  Java however you can
  > When writing components use objects and object hierarchies
    to organize related objects and prevent naming collision



                                                                 9
Example: Create a top level object BLUEPRINTS which
acts in a sense like a namespace for related objects
// 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(quot;id-1quot;, 5);
cart.addItem(quot;id-2quot;, 10);                                    10
Use the prototype
property
Use the prototype property
• Use it to define shared behavior and to extend
  objects
• The prototype property is a language feature of
  JavaScript
  > The property is available on all objects




                                                    12
Example: Usage of “prototype” property

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();


                                                                                           13
Example: Usage of “prototype” property
// Declare a shared addItem and calcualteTotal function and adds them
// as a property of the SmartCart prototype member.
Cart.prototype.addItem = function(id,name,desc,price) {
         this.items.push(new Item(id,name,desc,price));
}
Cart.prototype.calculateTotal = function() {
         for (var l=0; l < this.items.length; l++) {
               this.total = this.total + this.items[l].price;
         }
         return this.total;
}
// Create an instance of a Cart and add an item
var cart = new SmartCart();
cart.addItem(quot;id-1quot;,quot;Paperquot;, quot;Something you write onquot;, 5);
cart.addItem(quot;id-1quot;,quot;Penquot;, quot;Soemthing you write withquot;, 3);
alert(quot;total is: quot; + cart.calculateTotal());

                                                                        14
Write reusable JavaScript
Write reusable JavaScript

• JavaScript should not be tied to a specific
  component unless absolutely necessary
• Consider not hard coding data in your functions that
  can be parameterized




                                                         16
Example: Reusable JavaScript function
// The doSearch() function in this example can be reused because it is
// parameterized with the String id of the element, service URL, and the <div>
// to update. This script could later be used in another page or application
<script type=quot;text/javascriptquot;>
          doSearch(serviceURL, srcElement, targetDiv) {
               var targetElement = document.getElementById(srcElement);
               var targetDivElement = document.getElementById(targetDiv);
               // get completions based on serviceURL and srcElement.value
               // update the contents of the targetDiv element
          }
</script>
<form onsubmit=quot;return false;quot;>
        Name: <input type=quot;inputquot; id=quot;ac_1quot; autocomplete=quot;falsequot;
                   onkeyup=quot;doSearch('nameSearch','ac_1','div_1')quot;>
        City: <input type=quot;inputquot; id=quot;ac_2quot; autocomplete=quot;falsequot;
                   onkeyup=quot;doSearch('citySearch','ac_2','div_2')quot;>
        <input type=quot;buttonquot; value=quot;Submitquot;>
</form>
<div class=quot;completequot; id=quot;div_1quot;></div>
<div class=quot;completequot; id=quot;div_2quot;></div>
                                                                                 17
Use object literals as
flexible function
parameters
Object Literals

• Object literals are objects defined using braces ({})
  that contain a set of comma separated key value
  pairs much like a map in Java
• Example
  > {key1: quot;stringValuequot;, key2: 2, key3: ['blue','green','yellow']}
• Object literals are very handy in that they can be
  used as arguments to a function
• Object literals should not be confused with JSON
  which has similar syntax

                                                                      19
Example: Usage of Object Literals as
parameters
function doSearch(serviceURL, srcElement, targetDiv) {
        // Create object literal
        var params = {service: serviceURL, method: quot;getquot;, type: quot;text/xmlquot;};
        // Pass it as a parameter
        makeAJAXCall(params);
}
// This function does not need to change
function makeAJAXCall(params) {
          var serviceURL = params.service;
          ...
 }




                                                                               20
Example: Usage of Object Literals as
parameters - Anonymous Object Literals
function doSearch() {
         makeAJAXCall({serviceURL: quot;fooquot;,
                       method: quot;getquot;,
                       type: quot;text/xmlquot;,
                       callback: function(){alert('call done');}
                       });
 }
function makeAJAXCall(params) {
         var req = // getAJAX request;
         req.open(params.serviceURL, params.method, true);
         req.onreadystatechange = params.callback;
         ...
}




                                                                   21
Load JavaScript
on Demand
Load JavaScript On Demand

• If you have a large library or set of libraries you
  don't need to load everything when a page is
  loaded
• JavaScript may be loaded dynamically at runtime
  using a library such as JSAN or done manually
  by using AJAX to load JavaScript code and
  calling eval() on the JavaScript



                                                        23
Example: Load JavaScript On Demand

// Suppose the following is captured as cart.js file
function Cart () {
     this.items = [ ];
     this.checkout = function() {
                                 // checkout logic
                                 }
 }
---------------------------------------------------------------------
// get cart.js using an AJAX request
eval(javascriptText);
var cart = new Cart();
// add items to the cart
cart.checkout();



                                                                        24
Clean separation of
Content, CSS, and
JavaScript
Separation of content, CSS, and
JavaScript
• A rich web application user interface is made up of
  > content (HTML/XHTML)
  > styles (CSS)
  > JavaScript
• Separating the CSS styles from the JavaScript is a
  practice which will make your code more
  manageable, easier to read, and easier to customize
• Place CSS and JavaScript code in separate files
• Optimize the bandwidth usage by having CSS and
  JavaScript file loaded only once
                                                        26
Example: Bad Practice

<style>
#Styles
</style>
<script type=quot;text/javascriptquot;>
// JavaScript logic
<script>
<body>The quick brown fox...</body>




                                      27
Example: Good Practice

<link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;cart.cssquot;>
<script type=quot;text/javascriptquot; src=quot;cart.jsquot;>
<body>The quick brown fox...</body>




                                                          28
Reduce the size of
JavaScript file
Reduce the size of JavaScript file

• Remove the white spaces and shortening the names
  of variables and functions in a file
• While in development mode keep your scripts
  readable so that they may be debugged easier
• Consider compressing your JavaScript resources
  when you deploy your application
• If you use a 3rd party JavaScript library use the
  compressed version if one is provided.
  > Example compression tool: ShrinkSafe

                                                  30
JavaScript
Best Practices


Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com

More Related Content

What's hot

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
Simon Willison
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
Mohammed Sazid Al Rashid
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
Doris Chen
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 

What's hot (20)

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 

Similar to Java Script Best Practices

OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
Gunjan Kumar
 
Professional JavaScript Development - Creating Reusable Code
Professional JavaScript Development -  Creating Reusable CodeProfessional JavaScript Development -  Creating Reusable Code
Professional JavaScript Development - Creating Reusable CodeWildan Maulana
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
bcruhl
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
Sony Jain
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
borkweb
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsZohar Arad
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
Divante
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
David Jacobs
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
stephskardal
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
anjani pavan kumar
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
 
Java script object model
Java script object modelJava script object model
Java script object modelJames Hsieh
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Scriptccherubino
 
Scala, XML and GAE
Scala, XML and GAEScala, XML and GAE
Scala, XML and GAE
markryall
 

Similar to Java Script Best Practices (20)

OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
Professional JavaScript Development - Creating Reusable Code
Professional JavaScript Development -  Creating Reusable CodeProfessional JavaScript Development -  Creating Reusable Code
Professional JavaScript Development - Creating Reusable Code
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Java script object model
Java script object modelJava script object model
Java script object model
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
Scala, XML and GAE
Scala, XML and GAEScala, XML and GAE
Scala, XML and GAE
 

Recently uploaded

IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
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
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
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
 
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
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
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
 
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
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
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
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
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
 
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
 

Recently uploaded (20)

IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
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
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
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...
 
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
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
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...
 
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...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
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...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
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...
 
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
 

Java Script Best Practices

  • 1. JavaScript Best Practices Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com
  • 2. Disclaimer & Acknowledgments • Even though Sang Shin is a full-time employee of Sun Microsystems, the contents here are created as his own personal endeavor and thus does not necessarily reflect any official stance of Sun Microsystems on any particular technology • Acknowledgments > The contents of this presentation was created from “JavaScript recommendations for AJAX component writers” written by Greg Murray > https://blueprints.dev.java.net/bpcatalog/conventions/javascript- recommendations.html 2
  • 3. Topics • Use Object-oriented JavaScript • Use Object hierarchy • Use the prototype property • Write reusable JavaScript code • Use Object literals as function parameters • Load JavaScript on demand • Clean separation of content, CSS, and JavaScript • Reduce the size of JavaScript file 3
  • 5. Use Object Oriented JavaScript • Provides better reusability of the code • Enables your objects to be better organized • Allow for dynamic loading of objects 5
  • 6. Example: Cart Object in JavaScript // The Cart object above provides basic support for maintaining // // an internal array of Item objects function Cart() { this.items = []; } function Item (id,name,desc,price) { this.id = id; this.name = name; this.desc = desc; this.price = price; } // Create an instance of the Cart and add items var cart = new Cart(); cart.items.push(new Item(quot;id-1quot;,quot;Paperquot;,quot;something you write onquot;,5)); cart.items.push(new Item(quot;id-2quot;,quot;Penquot;, quot;Something you write withquot;,3)); var total = 0; for (var l = 0; l < cart.items.length; l++) { total = total + cart.items[l].price; } 6
  • 7. Example: Comparable Java Code public class Cart { private ArrayList items = new ArrayList(); public ArrayList getItems() { return items; } } public class Item { private String id; private String name; private String desc; private double price; public Item(String id, String name, String desc, double price) { this.id = id; this.name = name; this.desc = desc; this.price = price; } public String getId() {return id;} public String getName() {return name;} public String getDesc() {return desc;} public float getPrice() {return price;} } 7
  • 9. Use Object Hierarchies to Organize JavaScript Objects to Avoid Name Collision • In JavaScript there is the potential for object names to collide > In Java language, package names are used to prevent naming collisions • JavaScript does not provide package names like Java however you can > When writing components use objects and object hierarchies to organize related objects and prevent naming collision 9
  • 10. Example: Create a top level object BLUEPRINTS which acts in a sense like a namespace for related objects // 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(quot;id-1quot;, 5); cart.addItem(quot;id-2quot;, 10); 10
  • 12. Use the prototype property • Use it to define shared behavior and to extend objects • The prototype property is a language feature of JavaScript > The property is available on all objects 12
  • 13. Example: Usage of “prototype” property 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(); 13
  • 14. Example: Usage of “prototype” property // Declare a shared addItem and calcualteTotal function and adds them // as a property of the SmartCart prototype member. Cart.prototype.addItem = function(id,name,desc,price) { this.items.push(new Item(id,name,desc,price)); } Cart.prototype.calculateTotal = function() { for (var l=0; l < this.items.length; l++) { this.total = this.total + this.items[l].price; } return this.total; } // Create an instance of a Cart and add an item var cart = new SmartCart(); cart.addItem(quot;id-1quot;,quot;Paperquot;, quot;Something you write onquot;, 5); cart.addItem(quot;id-1quot;,quot;Penquot;, quot;Soemthing you write withquot;, 3); alert(quot;total is: quot; + cart.calculateTotal()); 14
  • 16. Write reusable JavaScript • JavaScript should not be tied to a specific component unless absolutely necessary • Consider not hard coding data in your functions that can be parameterized 16
  • 17. Example: Reusable JavaScript function // The doSearch() function in this example can be reused because it is // parameterized with the String id of the element, service URL, and the <div> // to update. This script could later be used in another page or application <script type=quot;text/javascriptquot;> doSearch(serviceURL, srcElement, targetDiv) { var targetElement = document.getElementById(srcElement); var targetDivElement = document.getElementById(targetDiv); // get completions based on serviceURL and srcElement.value // update the contents of the targetDiv element } </script> <form onsubmit=quot;return false;quot;> Name: <input type=quot;inputquot; id=quot;ac_1quot; autocomplete=quot;falsequot; onkeyup=quot;doSearch('nameSearch','ac_1','div_1')quot;> City: <input type=quot;inputquot; id=quot;ac_2quot; autocomplete=quot;falsequot; onkeyup=quot;doSearch('citySearch','ac_2','div_2')quot;> <input type=quot;buttonquot; value=quot;Submitquot;> </form> <div class=quot;completequot; id=quot;div_1quot;></div> <div class=quot;completequot; id=quot;div_2quot;></div> 17
  • 18. Use object literals as flexible function parameters
  • 19. Object Literals • Object literals are objects defined using braces ({}) that contain a set of comma separated key value pairs much like a map in Java • Example > {key1: quot;stringValuequot;, key2: 2, key3: ['blue','green','yellow']} • Object literals are very handy in that they can be used as arguments to a function • Object literals should not be confused with JSON which has similar syntax 19
  • 20. Example: Usage of Object Literals as parameters function doSearch(serviceURL, srcElement, targetDiv) { // Create object literal var params = {service: serviceURL, method: quot;getquot;, type: quot;text/xmlquot;}; // Pass it as a parameter makeAJAXCall(params); } // This function does not need to change function makeAJAXCall(params) { var serviceURL = params.service; ... } 20
  • 21. Example: Usage of Object Literals as parameters - Anonymous Object Literals function doSearch() { makeAJAXCall({serviceURL: quot;fooquot;, method: quot;getquot;, type: quot;text/xmlquot;, callback: function(){alert('call done');} }); } function makeAJAXCall(params) { var req = // getAJAX request; req.open(params.serviceURL, params.method, true); req.onreadystatechange = params.callback; ... } 21
  • 23. Load JavaScript On Demand • If you have a large library or set of libraries you don't need to load everything when a page is loaded • JavaScript may be loaded dynamically at runtime using a library such as JSAN or done manually by using AJAX to load JavaScript code and calling eval() on the JavaScript 23
  • 24. Example: Load JavaScript On Demand // Suppose the following is captured as cart.js file function Cart () { this.items = [ ]; this.checkout = function() { // checkout logic } } --------------------------------------------------------------------- // get cart.js using an AJAX request eval(javascriptText); var cart = new Cart(); // add items to the cart cart.checkout(); 24
  • 25. Clean separation of Content, CSS, and JavaScript
  • 26. Separation of content, CSS, and JavaScript • A rich web application user interface is made up of > content (HTML/XHTML) > styles (CSS) > JavaScript • Separating the CSS styles from the JavaScript is a practice which will make your code more manageable, easier to read, and easier to customize • Place CSS and JavaScript code in separate files • Optimize the bandwidth usage by having CSS and JavaScript file loaded only once 26
  • 27. Example: Bad Practice <style> #Styles </style> <script type=quot;text/javascriptquot;> // JavaScript logic <script> <body>The quick brown fox...</body> 27
  • 28. Example: Good Practice <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;cart.cssquot;> <script type=quot;text/javascriptquot; src=quot;cart.jsquot;> <body>The quick brown fox...</body> 28
  • 29. Reduce the size of JavaScript file
  • 30. Reduce the size of JavaScript file • Remove the white spaces and shortening the names of variables and functions in a file • While in development mode keep your scripts readable so that they may be debugged easier • Consider compressing your JavaScript resources when you deploy your application • If you use a 3rd party JavaScript library use the compressed version if one is provided. > Example compression tool: ShrinkSafe 30
  • 31. JavaScript Best Practices Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com