SlideShare a Scribd company logo
1 of 18
Download to read offline
Javascript + Ajax Basics


        Richard Paul
       Kiwiplan NZ Ltd
       30th Jan 2009
Javascript the Language



JavaScript is a scripting language widely used for client-side
web development. ... It is a dynamic, weakly typed, prototype-
based language with first-class functions.

 -- http://en.wikipedia.org/wiki/Javascript
Declaring Variables

var greeting = 'Hello'
var greeting = 'Hello'; // Semicolons are optional
var greeting = quot;Helloquot; // Single & double quotes are
                        // equivalent

var date = new Date()

// Array
var pets = ['cat', 'dog', 'fish']

// Map
var petNames = {cat:'Garfield', dog:'Snoopy', fish:'Nemo'}

// Globally accessible
greeting = 'Hello World'
Functions & Function Scope
Javascript supports function scope, but not block scope.
(Javascript 1.7 introduced 'let' for block scope, not supported in IE)

                                     // This will reassign x to 2, not
// Legal
                                     shadow x (as seen in Java etc).
function funA(num) {                 function funB(num) {
  if (i % 2 == 0) {                      var x = 1
    var x = 10                           if (num < 10) {
  } else {                                 var x = 2
    var x = 20                           }
  }                                  }
  x *= 2
  return x
}
Functions as objects

// Define a function called funA
function funA() {}

// Define a function, assign to variable funB
var funB = function() {}

// Scoped functions
function init() {
  var funC = function() { alert('hi') }
  funC() // OK
}
init()
funC() // => ReferenceError: funC is not defined
Javascript conditionals

                           // Ternery operator
// Javascript truth

                           function doubleOrNothing(x) {
// undefined is false
                             return x % 2 == 0 ? x*=2 : 0
var x
                           }
if (x) {                   doubleOrNothing(2) // => 4
  // Won't reach here      doubleOrNothing(3) // => 0
}

// empty string is false
                           // Default values
var x = ''
                           function X(num) {
if (x) {
                             this.num = num || 0
    // Won't reach here
                           }
}
Optional function arguments

// Adds x, y and an optional z argument
function adder(x, y, z) {
  var value = x + y
  if (z) {
    value += z
  }
  return value
}

adder()             //   =>   undefined + undefined = NaN
adder(2)            //   =>   2 + undefined = NaN
adder(2, 3)         //   =>   5
adder(2, 3, 4)      //   =>   9
adder(2, 3, 4, 5)   //   =>   9, last argument ignored
A better adder
(the arguments keyword)

function adder() {
  var total = 0
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i]
  }
  return total
}

adder()        // => 0
adder(1)       // => 1
adder(1, 2)    // => 3
Closures
Closures wrap a function, and its environment (variables) to allow it to
be executed later.

function init() {
  var num = 10
  function addNum(myNum) {
    return num + myNum
  }
  return addNum
}

var myAdder = init() // Creates a closure
myAdder(1) // => 11
Defining Objects
function Counter(num) {
  this.num = num || 0
  this.increment = function() {
    this.num++
  }
  this.decrement = function() {
    this.num--
  }
  this.add = function(otherNum) {
    this.num += otherNum
  }
}

While this is simple, it is inefficient as the functions are
defined every time a Counter object is created.
-- https://developer.mozilla.org/.../ClosurePerformance
Exceptions

openMyFile()
try {
   writeMyFile(theData) // This may throw a error
} catch(e) {
   handleError(e) // Handle any errors
} finally {
   closeMyFile() // Always close the resource
}

-- https://developer.mozilla.org/.../try...catch_Statement
Regex
// Literal
var regex = /d+/
// Object
var regex = new Regex('d+')

// Extract hash from a URL
// e.g. http://example.com/#example2
function extractHash(url) {
  var matches = url.match(/#.*/)
  if (matches) {
    return matches[0]
  }
  return '' // Default to empty string if no hash
}

extractHash('http://example.com/#example2')   // =>
#example2
AJAX - Asynchronous Javascript and XML

AJAX is the general term relating to web development
techniques used to update pages dynamically.

Is a misnomer as requests aren't required to be asynchronous
or return XML (any text can be returned).

XmlHttpRequest is the underlying object used to make
requests to a server without requiring a page reload.
AJAX - GET

Retrieve information from a server without a page load.

var request = new XMLHttpRequest()
request.open('GET', 'service/time', true)
request.onreadystatechange = function () {
  if (request.readyState == 4) { // 4 = loaded
    if (request.status == 200) { // 200 = success
      alert(request.responseText) // or responseXML
    }
    else {
      alert('Error loading page: ' + request.status)
    }
  }
}
request.send(null)
AJAX - POST

Send information to a server without a page load.

var url = quot;theUrlquot;
var params = quot;name=Groovy&speaker=Kuganquot;
http.open(quot;POSTquot;, url, true)

http.setRequestHeader(quot;Content-typequot;, quot;application/x-
  www-form-urlencodedquot;)
http.setRequestHeader(quot;Content-lengthquot;, params.length)
http.setRequestHeader(quot;Connectionquot;, quot;closequot;)

http.onreadystatechange = function() {
  // Do something with the response
}
http.send(params)
DOM Manipulation
Document Object Model - The object representation of an XML
page (the structure of a web page).
document.getElementById('myTextbox').value = 'new value'

var content = document.getElementById('myContent')
content.innerHTML = 'new content'

// Get elements for a certain tag, change link name.
var links = document.getElementsByTagName('a')
for (var i = 0; i < links.length; i++) {
  links[i].innerHTML += ' :-)' // Appends a smiley
}

// Add element to page
var div = document.createElement('div')
div.innerHTML = 'This is some content'
document.body.appendChild(div)
Javascript isn't just for web browsers

While Javascript is most widly used for client side scipting in a
browser, it is a fully fledged language and can be used
anywhere.

   Rhino - Open source Javascript engine.
   AppJet - 'Instant web programming', server side javascript
   Jaxer - Server side javascript
Useful Resources

 Javascript Console (live demo)
    http://nzrichardp:9090/AjaxServer/ (session 1)
    http://nzrichardp:9091/AjaxServer/ (session 2)
 Live Demo source (grails app, Kiwiplan CVS)
    Install Java + Grails
    Launch with 'grails run-app'
 Mozilla Javascript Reference
 W3 Spec for XmlHttpRequest
 Learning Advanced Javascript
 Javascript Closures
    Mozilla Developer
    Stack Overflow

More Related Content

What's hot

Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
Kim Hunmin
 

What's hot (20)

JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
Day 1
Day 1Day 1
Day 1
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
The State of JavaScript
The State of JavaScriptThe State of JavaScript
The State of JavaScript
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeus
 
Groovy
GroovyGroovy
Groovy
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 

Viewers also liked

Javascript ajax tutorial
Javascript ajax tutorialJavascript ajax tutorial
Javascript ajax tutorial
Vlad Posea
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
Theo Jungeblut
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
hchen1
 

Viewers also liked (17)

Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc Containers
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Javascript ajax tutorial
Javascript ajax tutorialJavascript ajax tutorial
Javascript ajax tutorial
 
Understanding Javascript AJAX - Imrokraft
Understanding Javascript AJAX - ImrokraftUnderstanding Javascript AJAX - Imrokraft
Understanding Javascript AJAX - Imrokraft
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 

Similar to Javascript & Ajax Basics

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 

Similar to Javascript & Ajax Basics (20)

ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Txjs
TxjsTxjs
Txjs
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 

More from Richard Paul (8)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Javascript & Ajax Basics

  • 1. Javascript + Ajax Basics Richard Paul Kiwiplan NZ Ltd 30th Jan 2009
  • 2. Javascript the Language JavaScript is a scripting language widely used for client-side web development. ... It is a dynamic, weakly typed, prototype- based language with first-class functions. -- http://en.wikipedia.org/wiki/Javascript
  • 3. Declaring Variables var greeting = 'Hello' var greeting = 'Hello'; // Semicolons are optional var greeting = quot;Helloquot; // Single & double quotes are // equivalent var date = new Date() // Array var pets = ['cat', 'dog', 'fish'] // Map var petNames = {cat:'Garfield', dog:'Snoopy', fish:'Nemo'} // Globally accessible greeting = 'Hello World'
  • 4. Functions & Function Scope Javascript supports function scope, but not block scope. (Javascript 1.7 introduced 'let' for block scope, not supported in IE) // This will reassign x to 2, not // Legal shadow x (as seen in Java etc). function funA(num) { function funB(num) { if (i % 2 == 0) { var x = 1 var x = 10 if (num < 10) { } else { var x = 2 var x = 20 } } } x *= 2 return x }
  • 5. Functions as objects // Define a function called funA function funA() {} // Define a function, assign to variable funB var funB = function() {} // Scoped functions function init() { var funC = function() { alert('hi') } funC() // OK } init() funC() // => ReferenceError: funC is not defined
  • 6. Javascript conditionals // Ternery operator // Javascript truth function doubleOrNothing(x) { // undefined is false return x % 2 == 0 ? x*=2 : 0 var x } if (x) { doubleOrNothing(2) // => 4 // Won't reach here doubleOrNothing(3) // => 0 } // empty string is false // Default values var x = '' function X(num) { if (x) { this.num = num || 0 // Won't reach here } }
  • 7. Optional function arguments // Adds x, y and an optional z argument function adder(x, y, z) { var value = x + y if (z) { value += z } return value } adder() // => undefined + undefined = NaN adder(2) // => 2 + undefined = NaN adder(2, 3) // => 5 adder(2, 3, 4) // => 9 adder(2, 3, 4, 5) // => 9, last argument ignored
  • 8. A better adder (the arguments keyword) function adder() { var total = 0 for (var i = 0; i < arguments.length; i++) { total += arguments[i] } return total } adder() // => 0 adder(1) // => 1 adder(1, 2) // => 3
  • 9. Closures Closures wrap a function, and its environment (variables) to allow it to be executed later. function init() { var num = 10 function addNum(myNum) { return num + myNum } return addNum } var myAdder = init() // Creates a closure myAdder(1) // => 11
  • 10. Defining Objects function Counter(num) { this.num = num || 0 this.increment = function() { this.num++ } this.decrement = function() { this.num-- } this.add = function(otherNum) { this.num += otherNum } } While this is simple, it is inefficient as the functions are defined every time a Counter object is created. -- https://developer.mozilla.org/.../ClosurePerformance
  • 11. Exceptions openMyFile() try { writeMyFile(theData) // This may throw a error } catch(e) { handleError(e) // Handle any errors } finally { closeMyFile() // Always close the resource } -- https://developer.mozilla.org/.../try...catch_Statement
  • 12. Regex // Literal var regex = /d+/ // Object var regex = new Regex('d+') // Extract hash from a URL // e.g. http://example.com/#example2 function extractHash(url) { var matches = url.match(/#.*/) if (matches) { return matches[0] } return '' // Default to empty string if no hash } extractHash('http://example.com/#example2') // => #example2
  • 13. AJAX - Asynchronous Javascript and XML AJAX is the general term relating to web development techniques used to update pages dynamically. Is a misnomer as requests aren't required to be asynchronous or return XML (any text can be returned). XmlHttpRequest is the underlying object used to make requests to a server without requiring a page reload.
  • 14. AJAX - GET Retrieve information from a server without a page load. var request = new XMLHttpRequest() request.open('GET', 'service/time', true) request.onreadystatechange = function () { if (request.readyState == 4) { // 4 = loaded if (request.status == 200) { // 200 = success alert(request.responseText) // or responseXML } else { alert('Error loading page: ' + request.status) } } } request.send(null)
  • 15. AJAX - POST Send information to a server without a page load. var url = quot;theUrlquot; var params = quot;name=Groovy&speaker=Kuganquot; http.open(quot;POSTquot;, url, true) http.setRequestHeader(quot;Content-typequot;, quot;application/x- www-form-urlencodedquot;) http.setRequestHeader(quot;Content-lengthquot;, params.length) http.setRequestHeader(quot;Connectionquot;, quot;closequot;) http.onreadystatechange = function() { // Do something with the response } http.send(params)
  • 16. DOM Manipulation Document Object Model - The object representation of an XML page (the structure of a web page). document.getElementById('myTextbox').value = 'new value' var content = document.getElementById('myContent') content.innerHTML = 'new content' // Get elements for a certain tag, change link name. var links = document.getElementsByTagName('a') for (var i = 0; i < links.length; i++) { links[i].innerHTML += ' :-)' // Appends a smiley } // Add element to page var div = document.createElement('div') div.innerHTML = 'This is some content' document.body.appendChild(div)
  • 17. Javascript isn't just for web browsers While Javascript is most widly used for client side scipting in a browser, it is a fully fledged language and can be used anywhere. Rhino - Open source Javascript engine. AppJet - 'Instant web programming', server side javascript Jaxer - Server side javascript
  • 18. Useful Resources Javascript Console (live demo) http://nzrichardp:9090/AjaxServer/ (session 1) http://nzrichardp:9091/AjaxServer/ (session 2) Live Demo source (grails app, Kiwiplan CVS) Install Java + Grails Launch with 'grails run-app' Mozilla Javascript Reference W3 Spec for XmlHttpRequest Learning Advanced Javascript Javascript Closures Mozilla Developer Stack Overflow