SlideShare a Scribd company logo
Learning to Love
JavaScript

G l e n n Va n d e r b u r g
glv@vanderburg.org
About Me
Programmer since (gulp) 1979
Paid programmer since 1985
Java programmer since January 1995
Co-founder of JavaMUG
Author of first advanced Java book
Speaker at No Fluff, Just Stuff since 2003
Independent consultant, trainer, and speaker
Ruby, Agile, TDD, JavaScript, Ajax
About This Talk

My full introduction to JavaScript is 3 hours
… and it could easily be much longer.

This talk does get technical …
But first, it’s worth recalling how we got here.
Part I

Comfortable
Confusion
Cast Your Mind Back …
January 1995: first public demonstration of Java
May 1995: Netscape licenses Java
October 1995: Navigator 2.0B1 supports Java
… and we hear the first mention of a web-page-based scripting
language called LiveScript.
The web is all abuzz about the coolness and potential of applets.

December 1995: Netscape renames LiveScript to
JavaScript and unveils it in Navigator 2.0B3
March 1996: First JavaScript talk at JavaMUG (by Greg
Graham)
A Bad Beginning
The decision to link JavaScript with Java—in
name and in syntax—proved to be a terrible one.
Clearly, Java programmers were in the best
position to understand and begin teaching it,
right?
“It’s a Toy!”
We early Java programmers took one look at
JavaScript and were revolted.
“Everything’s public!”
“No subclassing!”
“You can add and remove methods on existing objects!”
“You can change a property to a method!”
“I don’t know how to understand this language!!!”

JavaScript was a 10-day hack that got shipped.
We could tell.
The Result
Java programmers say “Avoid JavaScript.”
Keep all your logic on the server.
That’s where it belongs.
Use a real programming language.

Second JavaScript talk at JavaMUG?
George Lawniczak, “Ajax 101”, March 2006
A 10-year gap
Part II

Collateral
Damage
Then, Things Got Ugly
Applets failed.
With nothing else useful to do, JavaScript became a
tool for flash and dazzle.

Widespread abuse.
Annoying layers that obscured the useful part of the
page.
Poorly tested JavaScript. Runtime bugs.
Security issues that prompted people to turn
JavaScript off.
Flashing images, scrolling status bars. Blechh.
Nature Abhors
a Vacuum
Java people showed no interest in learning to use
JavaScript well.
So the page designers filled the gap.
Widespread examples of poor JavaScript style.
Some in pages, some in books.
Nearly everyone learned JavaScript from those examples.
They failed to see the potential, except for visual effects.

Learning a language by example works well …
if the language is similar to what you already know.
You Ain’t Seen Ugly
Yet
Then: The Browser Wars
JavaScript was a primary weapon.
Along with the DOM

Rapid change, competing standards
Willful incompatibility
Infuriating bugs
… and Yet …
All along, I kept hearing people pay grudging
respect to JavaScript.
“It’s similar to NewtonScript.”
I knew enough about NewtonScript and its ancestor,
Self, to know that was a compliment.

“It would be great except for the browser.”
Part III

Reconstruction
End of Browser Wars
Netscape gives up.
Mozilla and Firefox call a truce.
Microsoft shifts bug ray to CSS.
JavaScript implementations are actually pretty
good.
IE includes XMLHttpRequest, and Mozilla
follows suit.
How long before Java programmers wake up and
notice the changed situation?
Signs of Life
2000: Brent Ashley
Remote Scripting Resources site: www.ashleyit.com/rs/
JSRS (JavaScript Remote Scripting) and RSLite

2000: Alex Russell
netWindows (which became nWidgets, which gave rise
to Dojo)

Brent and Alex (and a few others) began exploring
the power of JavaScript and Ajax, long before that
term was invented.
Growth Outside
the Browser
Also during this period, JavaScript became the
default choice for an embedded scripting and
extension language.
Flash (ActionScript is a dialect of JavaScript)
Adobe applications: Photoshop, Illustrator, Acrobat,
etc.
Cocoon
Mac OS X apps: Sherlock, Konfabulator, Dashboard
Mozilla platform
MKS SourceIntegrity
It’s Always Darkest
Before Dawn
I don’t know the whole story of this period.
I was asleep in Java land.

June 2003: David Raphael showed me
netWindows, and I woke up.
Part IV

Revolution
The Revolution Began
with Google
Google Mail
Google Suggest
Google Maps
You know the rest. Now there are uncounted
Ajax applications.
Toolkits, Frameworks,
Tools
Many JavaScript libraries and toolkits to choose
from.
Prototype, Scriptaculous, Dojo, OpenRico, MochiKit,
DWR, YUI, Kabuki, …

End-to-end web frameworks rolling in Ajax
support.
Rails, Tapestry, JSF, ASP.NET, Seaside, Struts,
WebWork, …

Specialized tools for Ajax development
Links, GWT, Hop, Echo2, OpenLaszlo, haXe, …
Part V

Livin’ la Vida Loca
– or –

No Rules,
Just Right
– or –

Stop Worrying
and Love the DOM
My First Fluent
JavaScript
Budgeting/forecasting/three-year-planning app
Restaurants
Groceries
Meals
Car
Plane
Taxis
Transportation
Grand Total

2007
500
300
800
400
2,400
200
3,000
3,800

2008
450
300
750
500
2,200
250
2,950
3,700

2009
Total
425
1,375
275
875
700
2,250
550
1,450
2,100
6,700
300
750
2,950
8,900
3,650 11,150
Solution:
The Totalizator
to•tal•i•za•tor ¦ tōtl-i zātər¦
noun
A machine for computing and showing totals,
especially a pari-mutuel machine showing the
total number and amounts of bets at a
racetrack.
(The American Heritage Dictionary of the English Language,
Fourth Edition)
Solution:
The Totalizator
Table marked with an id attribute
Total column marked with total-column class
Subtotal rows marked with subtotal-row class
Grand total row marked with grand-total class
new Totalizator(‘forecast_table’);
How the Totalizator
Worked
Find the table using
document.getElementByID(table_id).
Traverse it looking for cells of various types,
building quick-reference lists.
Total everything up and set content in all total
cells.
Set observers on text fields to prompt
recalculation when cells are updated.
Totalizator Methods
buildDependentCellLists()

doTotals()

findAllCells()

getNumberFromCell(cell)

registerRow(row)

registerDataRow(row)

registerSubtotalRow(row)

registerTotalRow(row)

sumCells(cells)

updateCells(dependents)

updateDependents(element)
So Far, So Good
But it was a CRUD app.
My first version of Totalizator was great for
Create and Update.
Not necessary for Delete

What about Read?
Looking for text fields to observe ... we just don’t find
any.
Only other problem is reading a number from a cell.
The Problem Method
buildDependentCellLists()

doTotals()

findAllCells()

getNumberFromCell(cell)

registerRow(row)

registerDataRow(row)

registerSubtotalRow(row)

registerTotalRow(row)

sumCells(cells)

updateCells(dependents)

updateDependents(element)
What To Do?
Add an if statement to getNumberFromCell.
Nope. Too clumsy and specialized.
Remember: the only numbers are 0, 1, and many.

Write a subclass! ReadOnlyTotalizator!
Seems wrong somehow.
Plus, JavaScript doesn’t directly support subclasses.

I know! Use the Strategy pattern!
Killing flies with a bazooka …
Stop Thinking Java!
Functions are first-class objects in JavaScript.
Methods are just functions attached to objects.
You can add methods to classes at any time.
(Even after instances have been created.)

Individual objects can have their own methods!
An Easy Solution
function Totalizator(table_id, gnfc_function) {
this.table_id = table_id;
this.getNumberFromCell = gnfc_function;
// process table and find cells
}
new Totalizator(‘forecast_table’, function(cell) {
// logic to get number out of cell
});
That’s Easy?

Easy for Glenn to implement, maybe.
Not so easy for someone to use.
You have to supply a missing method every time
you create an instance!!!
Yeah, It’s Easy
Nobody said I couldn’t supply some useful
implementations …
Totalizator.getNumberFromSimpleCell = function(cell) {
return Number(cell.innerHTML);
}
Totalizator.getNumberFromTextInputCell = function(cell) {
return Number(cell.children[0].value);
}
Totalizator.prototype.getNumberFromCell =
Totalizator.getNumberFromSimpleCell;
One Final Update
Quickly revisit the constructor:
function Totalizator(table_id, gnfc_function) {
this.table_id = table_id;
if (arguments.length > 1)
this.getNumberFromCell = gnfc_function;
// process table and find cells
}

Now there’s some flexibility when creating:
new Totalizator(‘forecast_table’);
new Totalizator(‘forecast_table’,
Totalizator.getNumberFromTextInputCell);
How Does That Feel?
Sloppy? Maybe, if you’re still thinking in Java.
JavaScript is dynamic for good reasons.

Overengineered? I don’t think so.
Took a tiny bit of effort.
Easy to document.
Nice and DRY.

But you have to know the language!
What We Had to Know
Functions are first-class objects in JavaScript.
Methods are just functions attached to objects.
You can add methods to classes at any time.
(Even after instances have been created.)

Individual objects can have their own methods.
“Class” “constructors” are just functions.
Functions can have their own properties.
The arguments array lets you reflect on the argument list.
You can call functions or methods with too few (or too many)
arguments.
When we use a language,
we should commit ourselves to
knowing it, being able to read it,
and writing it idiomatically.
—Ron Jeffries
“The august Waldemar Horwat—who
was at one time the lead JavaScript
developer at Netscape—once told me that
he considered JavaScript to be just
another syntax for Common Lisp. I’m
pretty sure he was being serious.”
—Eric Lippert
JavaScript Is Weird

… unless you know NewtonScript or Self
(or, to a lesser degree, Smalltalk or CLOS)

Let’s look at a couple of the more interesting
aspects.
Functions and
Scope
Functions Are Objects
The following two statements are equivalent:
function square(num) { return num*num; }
var square = function(num) { return num*num; };

You can use functions without names
Functions can (and do) have their own properties.
Functions
Without Names?

(function(a, b){ return a+b; })(3, 4);
Variable Scope
In global scope, variables are resolved through
the global object.
add(accum, incr)

global
accum: 1
incr: 2
add: <function>
Variable Scope
Let’s see what happens in the body of that
function.
function add(a, b) {
return a + b;
}
<call>
__parent__:
a: 1
b: 2
arguments: [1, 2]

global
accum: 1
incr: 2
add: <function>
Lexical Scope
function f(x, y) {
g(x);
}
function g(z) {
alert(z);
}
f(3, 4);
What does the scope
chain look like when
alert is called?

global
f: <function>
g: <function>
alert: <function>

<call>
__parent__:
z: 3
arguments: [3]
Lexical Scope
function f(x, y) {
function g(z) {
alert(y);
alert(z);
}
g(x);
}
f(3, 4);
Does this change the
scope chain?

global
f: <function>
alert: <function>

<f’s call>
__parent__:
g: <function>
x: 3
y: 4
arguments: [3, 4]

<g’s call>
__parent__:
z: 3
arguments: [3]
Variable Scope:
Closures
That works even for
anonymous functions:
function f(x, y) {
return function (z) {
alert(y);
alert(z);
}
}

global
f: <function>
g: <function>
alert: <function>

<f’s call>
__parent__:
x: 3
y: 4
arguments: [3, 4]

<g’s call>

g = f(3, 4);
g(5)

__parent__:
z: 5
arguments: [5]
Variable Scope:
Closures
As part of XMLHttpRequest’s API, you must
supply callback functions.
XHR won’t pass them any parameters.

What if, in response to one of the XHR events,
you want to do some fairly complicated
processing with an element?
Variable Scope:
Closures
function ajaxDazzle() {
if (xhr.readyState != 4) return;
elem = document.getElementByID(‘item_list’);
// do complicated stuff
}
// …
xhr.onreadystatechange = ajaxDazzle;
OK, but what if ‘item_list’ isn’t the only element
you need this for?
Variable Scope:
Closures
function ajaxDazzler(elem_id) {
return function() {
if (xhr.readyState != 4) return;
elem = document.getElementByID(elem_id);
// do complicated stuff
};
}
// …
xhr.onreadystatechange = ajaxDazzler(‘item_list’);
Instance Variables
and Methods
Instance Variables
in Java
object.prop;
What happens?
Java finds the value of prop directly in the object.

But where does it come from?
At creation, all instance variables are created based on
declarations in the class and all superclasses.
Instance Variables
in JavaScript
object.prop;
What happens?
JavaScript looks for the value of prop directly in the
object.
If not found there, it looks in the object referenced by
the __proto__ property (usually the constructor’s
prototype).
The search continues until prop is found or __proto__ is
null.
Instance Variables
in JavaScript
But where does it come from?
Properties are usually created by the constructor.
Sometimes they already exist on the prototype when
the instance is created.
Often they’re added (in either place) after creation,
whether by a method or from the outside.
Point
point1
__proto__:
x: 1
y: 2

<prototype>
__proto__: <other prototype>
constructor: <function Foo>
name: “unnamed”

prototype:
Methods in Java
object.method();
What happens?
Java looks for prop in the object’s class.
If it’s not there, look in superclass.
Continue until found or superclass is null.

But where does it come from?
All methods are declared within classes when the
classes are declared.
Methods in JavaScript
object.method();
What happens?
JavaScript looks for the value of method directly in the
object.
If not found there, it looks in the object referenced by
the __proto__ property (usually the constructor’s
prototype).
The search continues until method is found or
__proto__ is null.
Instance Variables
in JavaScript
But where does it come from?
Methods are usually set on the prototype before the
instance is created.
Sometimes they’re created by the constructor.
Often they’re added (in either place) after creation,
whether by a method or from the outside.
Point
point1
__proto__:
x: 1
y: 2
to_polar: <function>

<prototype>
__proto__: <other prototype>
constructor: <function Foo>
name: “unnamed”
distance: <function>

prototype:
Properties
and Methods
In Java, instance variables and methods are very
different.
In JavaScript, they’re the same.
They’re usually created in different ways, but that’s just
the way people do it.
Neither works exactly the way they do in Java.

This can come in handy!
Add methods to individual objects.
Add an instance variable to all existing instances.
There’s More …
It’s all incredibly handy, once you embrace the
JavaScript philosophy.
Would I build an application server with it?
Probably not.
I wouldn’t port Swing to it, either.

But it’s remarkably well suited for the
environment inside a web page.
The really important thing
about Ajax is that it’s tricked us
into adopting a really powerful
language when we wouldn’t have
chosen to do so on our own.
—Stuart Halloway
Ajax is a gateway drug
for JavaScript.
—Stuart Halloway

More Related Content

Viewers also liked

www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...
www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...
www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...
Daniel Deppe
 
Real software engineering
Real software engineeringReal software engineering
Real software engineering
atr2006
 
WordPressでサイト作成するときに知っておくといいことあれこれ
WordPressでサイト作成するときに知っておくといいことあれこれWordPressでサイト作成するときに知っておくといいことあれこれ
WordPressでサイト作成するときに知っておくといいことあれこれ
YUKI YAMAGUCHI
 
RailsWayCon: Multidimensional Data Analysis with JRuby
RailsWayCon: Multidimensional Data Analysis with JRubyRailsWayCon: Multidimensional Data Analysis with JRuby
RailsWayCon: Multidimensional Data Analysis with JRuby
Raimonds Simanovskis
 
IoTとDeep Learningで自宅警備員を育ててみる
IoTとDeep Learningで自宅警備員を育ててみるIoTとDeep Learningで自宅警備員を育ててみる
IoTとDeep Learningで自宅警備員を育ててみる
Yasuyuki Sugai
 
イマドキのExcelスクショの撮り方
イマドキのExcelスクショの撮り方イマドキのExcelスクショの撮り方
イマドキのExcelスクショの撮り方
Yoshitaka Kawashima
 

Viewers also liked (6)

www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...
www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...
www.onlinetexte.com | Pressemeldung 2011-08 | Textservice stellt neue Webseit...
 
Real software engineering
Real software engineeringReal software engineering
Real software engineering
 
WordPressでサイト作成するときに知っておくといいことあれこれ
WordPressでサイト作成するときに知っておくといいことあれこれWordPressでサイト作成するときに知っておくといいことあれこれ
WordPressでサイト作成するときに知っておくといいことあれこれ
 
RailsWayCon: Multidimensional Data Analysis with JRuby
RailsWayCon: Multidimensional Data Analysis with JRubyRailsWayCon: Multidimensional Data Analysis with JRuby
RailsWayCon: Multidimensional Data Analysis with JRuby
 
IoTとDeep Learningで自宅警備員を育ててみる
IoTとDeep Learningで自宅警備員を育ててみるIoTとDeep Learningで自宅警備員を育ててみる
IoTとDeep Learningで自宅警備員を育ててみる
 
イマドキのExcelスクショの撮り方
イマドキのExcelスクショの撮り方イマドキのExcelスクショの撮り方
イマドキのExcelスクショの撮り方
 

Similar to Glenn Vanderburg — Learning to love JavaScript

JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
Peter Hecker
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
Jonathan Fine
 
Javascript beginner-handbook
Javascript beginner-handbookJavascript beginner-handbook
Javascript beginner-handbook
Faina Fridman
 
javascript-beginner-handbook.pdf
javascript-beginner-handbook.pdfjavascript-beginner-handbook.pdf
javascript-beginner-handbook.pdf
RaviKumar76265
 
Groovy And Grails
Groovy And GrailsGroovy And Grails
Groovy And Grails
William Grosso
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Sujit Majety
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
Katy Allen
 
scala-intro
scala-introscala-intro
scala-intro
Manav Prasad
 
Languages used by web app development services remotestac x
Languages used by web app development services  remotestac xLanguages used by web app development services  remotestac x
Languages used by web app development services remotestac x
Remote Stacx
 
Gluecon 2014 - Bringing Node.js to the JVM
Gluecon 2014 - Bringing Node.js to the JVMGluecon 2014 - Bringing Node.js to the JVM
Gluecon 2014 - Bringing Node.js to the JVM
Jeremy Whitlock
 
Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distribution
Raymond Tay
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
Maxim Volgin
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
ChengHui Weng
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Modern_2.pptx for java
Modern_2.pptx for java Modern_2.pptx for java
Modern_2.pptx for java
MayaTofik
 
Graphql
GraphqlGraphql
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
Hitesh-Java
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
PawanMM
 
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docxLabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
DIPESH30
 

Similar to Glenn Vanderburg — Learning to love JavaScript (20)

JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Javascript beginner-handbook
Javascript beginner-handbookJavascript beginner-handbook
Javascript beginner-handbook
 
javascript-beginner-handbook.pdf
javascript-beginner-handbook.pdfjavascript-beginner-handbook.pdf
javascript-beginner-handbook.pdf
 
Groovy And Grails
Groovy And GrailsGroovy And Grails
Groovy And Grails
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
 
scala-intro
scala-introscala-intro
scala-intro
 
Languages used by web app development services remotestac x
Languages used by web app development services  remotestac xLanguages used by web app development services  remotestac x
Languages used by web app development services remotestac x
 
DSLs in JavaScript
DSLs in JavaScriptDSLs in JavaScript
DSLs in JavaScript
 
Gluecon 2014 - Bringing Node.js to the JVM
Gluecon 2014 - Bringing Node.js to the JVMGluecon 2014 - Bringing Node.js to the JVM
Gluecon 2014 - Bringing Node.js to the JVM
 
Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distribution
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Modern_2.pptx for java
Modern_2.pptx for java Modern_2.pptx for java
Modern_2.pptx for java
 
Graphql
GraphqlGraphql
Graphql
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docxLabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
 

Recently uploaded

Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
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
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
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
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
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
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
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
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
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
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
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
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

Glenn Vanderburg — Learning to love JavaScript

  • 1. Learning to Love JavaScript G l e n n Va n d e r b u r g glv@vanderburg.org
  • 2. About Me Programmer since (gulp) 1979 Paid programmer since 1985 Java programmer since January 1995 Co-founder of JavaMUG Author of first advanced Java book Speaker at No Fluff, Just Stuff since 2003 Independent consultant, trainer, and speaker Ruby, Agile, TDD, JavaScript, Ajax
  • 3. About This Talk My full introduction to JavaScript is 3 hours … and it could easily be much longer. This talk does get technical … But first, it’s worth recalling how we got here.
  • 5. Cast Your Mind Back … January 1995: first public demonstration of Java May 1995: Netscape licenses Java October 1995: Navigator 2.0B1 supports Java … and we hear the first mention of a web-page-based scripting language called LiveScript. The web is all abuzz about the coolness and potential of applets. December 1995: Netscape renames LiveScript to JavaScript and unveils it in Navigator 2.0B3 March 1996: First JavaScript talk at JavaMUG (by Greg Graham)
  • 6. A Bad Beginning The decision to link JavaScript with Java—in name and in syntax—proved to be a terrible one. Clearly, Java programmers were in the best position to understand and begin teaching it, right?
  • 7. “It’s a Toy!” We early Java programmers took one look at JavaScript and were revolted. “Everything’s public!” “No subclassing!” “You can add and remove methods on existing objects!” “You can change a property to a method!” “I don’t know how to understand this language!!!” JavaScript was a 10-day hack that got shipped. We could tell.
  • 8. The Result Java programmers say “Avoid JavaScript.” Keep all your logic on the server. That’s where it belongs. Use a real programming language. Second JavaScript talk at JavaMUG? George Lawniczak, “Ajax 101”, March 2006 A 10-year gap
  • 10. Then, Things Got Ugly Applets failed. With nothing else useful to do, JavaScript became a tool for flash and dazzle. Widespread abuse. Annoying layers that obscured the useful part of the page. Poorly tested JavaScript. Runtime bugs. Security issues that prompted people to turn JavaScript off. Flashing images, scrolling status bars. Blechh.
  • 11. Nature Abhors a Vacuum Java people showed no interest in learning to use JavaScript well. So the page designers filled the gap. Widespread examples of poor JavaScript style. Some in pages, some in books. Nearly everyone learned JavaScript from those examples. They failed to see the potential, except for visual effects. Learning a language by example works well … if the language is similar to what you already know.
  • 12. You Ain’t Seen Ugly Yet Then: The Browser Wars JavaScript was a primary weapon. Along with the DOM Rapid change, competing standards Willful incompatibility Infuriating bugs
  • 13. … and Yet … All along, I kept hearing people pay grudging respect to JavaScript. “It’s similar to NewtonScript.” I knew enough about NewtonScript and its ancestor, Self, to know that was a compliment. “It would be great except for the browser.”
  • 15. End of Browser Wars Netscape gives up. Mozilla and Firefox call a truce. Microsoft shifts bug ray to CSS. JavaScript implementations are actually pretty good. IE includes XMLHttpRequest, and Mozilla follows suit. How long before Java programmers wake up and notice the changed situation?
  • 16. Signs of Life 2000: Brent Ashley Remote Scripting Resources site: www.ashleyit.com/rs/ JSRS (JavaScript Remote Scripting) and RSLite 2000: Alex Russell netWindows (which became nWidgets, which gave rise to Dojo) Brent and Alex (and a few others) began exploring the power of JavaScript and Ajax, long before that term was invented.
  • 17. Growth Outside the Browser Also during this period, JavaScript became the default choice for an embedded scripting and extension language. Flash (ActionScript is a dialect of JavaScript) Adobe applications: Photoshop, Illustrator, Acrobat, etc. Cocoon Mac OS X apps: Sherlock, Konfabulator, Dashboard Mozilla platform MKS SourceIntegrity
  • 18. It’s Always Darkest Before Dawn I don’t know the whole story of this period. I was asleep in Java land. June 2003: David Raphael showed me netWindows, and I woke up.
  • 20. The Revolution Began with Google Google Mail Google Suggest Google Maps You know the rest. Now there are uncounted Ajax applications.
  • 21. Toolkits, Frameworks, Tools Many JavaScript libraries and toolkits to choose from. Prototype, Scriptaculous, Dojo, OpenRico, MochiKit, DWR, YUI, Kabuki, … End-to-end web frameworks rolling in Ajax support. Rails, Tapestry, JSF, ASP.NET, Seaside, Struts, WebWork, … Specialized tools for Ajax development Links, GWT, Hop, Echo2, OpenLaszlo, haXe, …
  • 22. Part V Livin’ la Vida Loca
  • 23. – or – No Rules, Just Right
  • 24. – or – Stop Worrying and Love the DOM
  • 25. My First Fluent JavaScript Budgeting/forecasting/three-year-planning app Restaurants Groceries Meals Car Plane Taxis Transportation Grand Total 2007 500 300 800 400 2,400 200 3,000 3,800 2008 450 300 750 500 2,200 250 2,950 3,700 2009 Total 425 1,375 275 875 700 2,250 550 1,450 2,100 6,700 300 750 2,950 8,900 3,650 11,150
  • 26. Solution: The Totalizator to•tal•i•za•tor ¦ tōtl-i zātər¦ noun A machine for computing and showing totals, especially a pari-mutuel machine showing the total number and amounts of bets at a racetrack. (The American Heritage Dictionary of the English Language, Fourth Edition)
  • 27. Solution: The Totalizator Table marked with an id attribute Total column marked with total-column class Subtotal rows marked with subtotal-row class Grand total row marked with grand-total class new Totalizator(‘forecast_table’);
  • 28. How the Totalizator Worked Find the table using document.getElementByID(table_id). Traverse it looking for cells of various types, building quick-reference lists. Total everything up and set content in all total cells. Set observers on text fields to prompt recalculation when cells are updated.
  • 30. So Far, So Good But it was a CRUD app. My first version of Totalizator was great for Create and Update. Not necessary for Delete What about Read? Looking for text fields to observe ... we just don’t find any. Only other problem is reading a number from a cell.
  • 32. What To Do? Add an if statement to getNumberFromCell. Nope. Too clumsy and specialized. Remember: the only numbers are 0, 1, and many. Write a subclass! ReadOnlyTotalizator! Seems wrong somehow. Plus, JavaScript doesn’t directly support subclasses. I know! Use the Strategy pattern! Killing flies with a bazooka …
  • 33. Stop Thinking Java! Functions are first-class objects in JavaScript. Methods are just functions attached to objects. You can add methods to classes at any time. (Even after instances have been created.) Individual objects can have their own methods!
  • 34. An Easy Solution function Totalizator(table_id, gnfc_function) { this.table_id = table_id; this.getNumberFromCell = gnfc_function; // process table and find cells } new Totalizator(‘forecast_table’, function(cell) { // logic to get number out of cell });
  • 35. That’s Easy? Easy for Glenn to implement, maybe. Not so easy for someone to use. You have to supply a missing method every time you create an instance!!!
  • 36. Yeah, It’s Easy Nobody said I couldn’t supply some useful implementations … Totalizator.getNumberFromSimpleCell = function(cell) { return Number(cell.innerHTML); } Totalizator.getNumberFromTextInputCell = function(cell) { return Number(cell.children[0].value); } Totalizator.prototype.getNumberFromCell = Totalizator.getNumberFromSimpleCell;
  • 37. One Final Update Quickly revisit the constructor: function Totalizator(table_id, gnfc_function) { this.table_id = table_id; if (arguments.length > 1) this.getNumberFromCell = gnfc_function; // process table and find cells } Now there’s some flexibility when creating: new Totalizator(‘forecast_table’); new Totalizator(‘forecast_table’, Totalizator.getNumberFromTextInputCell);
  • 38. How Does That Feel? Sloppy? Maybe, if you’re still thinking in Java. JavaScript is dynamic for good reasons. Overengineered? I don’t think so. Took a tiny bit of effort. Easy to document. Nice and DRY. But you have to know the language!
  • 39. What We Had to Know Functions are first-class objects in JavaScript. Methods are just functions attached to objects. You can add methods to classes at any time. (Even after instances have been created.) Individual objects can have their own methods. “Class” “constructors” are just functions. Functions can have their own properties. The arguments array lets you reflect on the argument list. You can call functions or methods with too few (or too many) arguments.
  • 40. When we use a language, we should commit ourselves to knowing it, being able to read it, and writing it idiomatically. —Ron Jeffries
  • 41. “The august Waldemar Horwat—who was at one time the lead JavaScript developer at Netscape—once told me that he considered JavaScript to be just another syntax for Common Lisp. I’m pretty sure he was being serious.” —Eric Lippert
  • 42. JavaScript Is Weird … unless you know NewtonScript or Self (or, to a lesser degree, Smalltalk or CLOS) Let’s look at a couple of the more interesting aspects.
  • 44. Functions Are Objects The following two statements are equivalent: function square(num) { return num*num; } var square = function(num) { return num*num; }; You can use functions without names Functions can (and do) have their own properties.
  • 46. Variable Scope In global scope, variables are resolved through the global object. add(accum, incr) global accum: 1 incr: 2 add: <function>
  • 47. Variable Scope Let’s see what happens in the body of that function. function add(a, b) { return a + b; } <call> __parent__: a: 1 b: 2 arguments: [1, 2] global accum: 1 incr: 2 add: <function>
  • 48. Lexical Scope function f(x, y) { g(x); } function g(z) { alert(z); } f(3, 4); What does the scope chain look like when alert is called? global f: <function> g: <function> alert: <function> <call> __parent__: z: 3 arguments: [3]
  • 49. Lexical Scope function f(x, y) { function g(z) { alert(y); alert(z); } g(x); } f(3, 4); Does this change the scope chain? global f: <function> alert: <function> <f’s call> __parent__: g: <function> x: 3 y: 4 arguments: [3, 4] <g’s call> __parent__: z: 3 arguments: [3]
  • 50. Variable Scope: Closures That works even for anonymous functions: function f(x, y) { return function (z) { alert(y); alert(z); } } global f: <function> g: <function> alert: <function> <f’s call> __parent__: x: 3 y: 4 arguments: [3, 4] <g’s call> g = f(3, 4); g(5) __parent__: z: 5 arguments: [5]
  • 51. Variable Scope: Closures As part of XMLHttpRequest’s API, you must supply callback functions. XHR won’t pass them any parameters. What if, in response to one of the XHR events, you want to do some fairly complicated processing with an element?
  • 52. Variable Scope: Closures function ajaxDazzle() { if (xhr.readyState != 4) return; elem = document.getElementByID(‘item_list’); // do complicated stuff } // … xhr.onreadystatechange = ajaxDazzle; OK, but what if ‘item_list’ isn’t the only element you need this for?
  • 53. Variable Scope: Closures function ajaxDazzler(elem_id) { return function() { if (xhr.readyState != 4) return; elem = document.getElementByID(elem_id); // do complicated stuff }; } // … xhr.onreadystatechange = ajaxDazzler(‘item_list’);
  • 55. Instance Variables in Java object.prop; What happens? Java finds the value of prop directly in the object. But where does it come from? At creation, all instance variables are created based on declarations in the class and all superclasses.
  • 56. Instance Variables in JavaScript object.prop; What happens? JavaScript looks for the value of prop directly in the object. If not found there, it looks in the object referenced by the __proto__ property (usually the constructor’s prototype). The search continues until prop is found or __proto__ is null.
  • 57. Instance Variables in JavaScript But where does it come from? Properties are usually created by the constructor. Sometimes they already exist on the prototype when the instance is created. Often they’re added (in either place) after creation, whether by a method or from the outside. Point point1 __proto__: x: 1 y: 2 <prototype> __proto__: <other prototype> constructor: <function Foo> name: “unnamed” prototype:
  • 58. Methods in Java object.method(); What happens? Java looks for prop in the object’s class. If it’s not there, look in superclass. Continue until found or superclass is null. But where does it come from? All methods are declared within classes when the classes are declared.
  • 59. Methods in JavaScript object.method(); What happens? JavaScript looks for the value of method directly in the object. If not found there, it looks in the object referenced by the __proto__ property (usually the constructor’s prototype). The search continues until method is found or __proto__ is null.
  • 60. Instance Variables in JavaScript But where does it come from? Methods are usually set on the prototype before the instance is created. Sometimes they’re created by the constructor. Often they’re added (in either place) after creation, whether by a method or from the outside. Point point1 __proto__: x: 1 y: 2 to_polar: <function> <prototype> __proto__: <other prototype> constructor: <function Foo> name: “unnamed” distance: <function> prototype:
  • 61. Properties and Methods In Java, instance variables and methods are very different. In JavaScript, they’re the same. They’re usually created in different ways, but that’s just the way people do it. Neither works exactly the way they do in Java. This can come in handy! Add methods to individual objects. Add an instance variable to all existing instances.
  • 62. There’s More … It’s all incredibly handy, once you embrace the JavaScript philosophy. Would I build an application server with it? Probably not. I wouldn’t port Swing to it, either. But it’s remarkably well suited for the environment inside a web page.
  • 63. The really important thing about Ajax is that it’s tricked us into adopting a really powerful language when we wouldn’t have chosen to do so on our own. —Stuart Halloway
  • 64. Ajax is a gateway drug for JavaScript. —Stuart Halloway