SlideShare a Scribd company logo
1 of 47
Exciting JavaScript
 What makes it unique, how to use it.

           Eugene Lazutkin
  Dallas, TX, ClubAjax on 3/2/2010


                  1
Disclaimer

• I will use JavaScript, JS, and ECMAScript
  interchangeably.
• The material is mostly based on
  ECMAScript 3.




                      2
Why JavaScript?
• Browsers.
• CommonJS (ex-ServerJS) is gaining steam.
• CouchDB uses it to define “views”.
• Node.js with its asynchronous event-based
  I/O is red hot.
• An explosion of JavaScript run-time
  environments and libraries.

                     3
JS the Language I
• JavaScript packages a formidable set of
  tools we can leverage to reduce
  complexity.
• While it doesn’t provide a direct support
  for some programming paradigms, it has
  proper tools for us to do it.



                      4
JS the Language II
• Following paradigms can be supported:
 • Object-oriented programming (OOP).
 • Functional programming (FP).
 • Aspect-oriented programming (AOP).
 • Event-driven programming (EDP).
 • Much more.
                    5
What we did last time
• We look into the JavaScript-specific
  language facilities to see what it offers.
• We dissected OOP and AOP paradigms.
• We mapped simple OOP and AOP
  paradigms on top of available constructs.



                       6
What we found
• 1st-class functions.
• Closures.
• Hash-based extendable objects.
• Duck-typing rules!
• OOP can be made with a language, rather
  than provided by a language.


                     7
Simple OOP
// our constructor
var Person = function(name){
 // our instance-level variables
 this.name = name;
};
// our methods and class-level variables/constants
Person.prototype = {
 answer: 42,
 say: function(msg){ alert(this.name + “: “ + msg); }
};




                         8
Simple AOP
// augmenting Person’s say()
var old = Person.prototype.say;
Person.prototype.say = function(msg){
 var newMsg = msg.toUpperCase();
 old.call(this, newMsg);
};


// WARNING: this augmentation doesn’t scale up
// well, use something like dojox.lang.aop




                           9
FP
Functional approach.




         10
FP: short intro I
• It is about representing algorithms as a
  composition of functions.
• It stresses out the algorithmic part of
  programming.
• It is not about states (unlike OOP), but
  about a control flow.


                      11
FP: short intro II
• Higher-order functions:
 • Can consume other functions as
    parameters.
 • Can return functions.
 • That’s where “function as a 1st-order
    value” pays off.


                       12
FP: short intro III
• Pure functions:
 • No side-effects.
 • Why? Easier to combine.
• Recursion is important:
 • We can do it JS too.

                   13
FP in JavaScript?
• Some pieces of our program can be
  functional (e.g., stateless).
• Some side-effects can be deemed “harmless
  for our purposes”.
 • They do not affect our algorithm.

                        14
FP in JavaScript
• Practical FP in JS:
 • Use adapters to customize components.
 • Combine components using chaining.
 • Convert flow statements into functions.
• While jQuery is not an FP toolkit, it has
  popularized the style.


                     15
FP: adapter example
• Remember our hack with “self = this”? We
  can adapt our functions/methods for that:
  function hitch(obj, name){
      return function(){
       var fn = typeof name == “string” ? obj[name] : name;
       return fn.apply(obj, arguments);
      };
  }




                             16
FP: using hitch
var queue = {
 stack: [],
 memorize: function(x){ this.stack.push(x); }
};
queue.memorize(2);
// or we can use it as a function with any context
var q = hitch(queue, “memorize”);
q(2);
q(3);




                         17
FP: control flow
• Control flow can be implemented as
  higher-order functions.
 • Traditionally iteration and recursion are
    major sources of programmer’s errors.
 • Cut’n’paste frequently breaks internal
    loop variables.


                      18
FP: “array extras”
• Back in Firefox 1.5 so-called “array extras”
  were introduced:
  • forEach(), every(), some(), map(), filter(),
    indexOf(), lastIndexOf().
  • Firefox 3 added: reduce(), reduceRight().
• They allow to process arrays as streams
  eliminating direct loops.

                       19
FP: process arrays
• “Array extras” allows writing very compact
  neatly piped data processing:
  var data = [...];
  var result = data.
   map(function(x){ return x * x; }).
   filter(function(x){ return x % 2 == 1; }).
   reduce(function(a, b){ return a + b; });




                           20
More on FP
• jQuery uses similar techniques on
  NodeList with great success.
• I wrote a blog post about FP in JS and how
  it is implemented in Dojo:
 • http://lazutkin.com/blog/2008/jan/12/
    functional-fun-javascript-dojo/


                      21
Inventory (cont.)
    Dynamic language.




           22
Code generation I
• JavaScript can compile text to an
  executable code with two constructs:
  • eval() – compile a string as JavaScript. Any
    valid JavaScript can be compiled.
  • new Function() – compile a function.
• We can generate code for fun and profit!
                      23
Code generation II
• Some environments do not allow code
  generation.
 • Sandboxes can prohibit it for security
    reasons.
 • ES5 strict mode doesn’t allow it. It works
    in ES5 strict mode with some caveats.
 • All browsers in normal mode support it.
                     24
Introspection I
• “for-in” loop enumerates all keys in an
  object.
  • Some keys can be hidden.
• Function.toString() can return a source
  code for a function.
  • Some implementations (e.g., mobile) do
    not support this feature.

                      25
Introspection II
• Function has some additional properties
  like “name” or “length”.
  • Some browsers do not support them.
• ES5 strict mode doesn’t allow inspection of
  “arguments.caller” and “arguments.callee”.



                     26
CG advantage
• Having CG around opens new vistas:
 • We can generate code custom-tailored
    (optimized) to a specific task completely
    on the fly.
 • We can use Domain-Specific Languages
    (DSL) to simplify our problems at hand.


                     27
DSL
Domain-specific languages and code generation.




                     28
Implementing DSL I
• DSL can be implemented in several layers:
 • By providing objects and libraries specific
    for our problem area.
    • Example: HTML DOM.
    • Example: CSS.
    • Example: JSON.
                     29
Implementing DSL II
• If our language supports it, we can provide
  special language constructs to make our
  tasks simpler:
  • Example: regular expressions in
    JavaScript.
  • Example: NodeList and jQuery, or
    dojo.query, or similar facilities of other
    libraries for HTML DOM and CSS.

                      30
Implementing DSL III
• Finally we can implement our own custom
  language, and interpret it, or compile it to
  our implementation language.
• Trade-offs are easy to assess: cost of
  abstraction (e.g., compile time) vs. run time.



                      31
HTML as DSL
// let’s “program” a list
var list = “
<ul>
 <li>Mike</li>
 <li>Bob</li>
</ul>”;
// let’s “interpret” it
ourDomNode.innerHTML = list;
// let’s read it back
var text = ourDomNode.innerHTML;




                            32
CSS as DSL
// CSS selector is used in dojo.query
// (all major libraries can do that nowadays)
dojo.query(“.myClass li”).
 style({
  color: “blue”,
  background: “yellow”
 });




                         33
JSON as DSL
// Let’s produce some JSON
var str = JSON.stringify({
 answer: 42,
 array: [1, 2, 3, 4],
 subObject: {name: “Mike”}
});


// old-school JSON “interpretation”
// (WARNING: don’t do it at home!)
var obj = eval(“(“ + str + ”)”);




                             34
DSL: lambdas I
• Our functional example (slide 20) was as
  compact as possible in JavaScript. But
  imagine that we had a way to reduce the
  functions we used?
• We could have something like that:
  var result =
   data.map(“x * x”).filter(“x % 2 == 1”).reduce(“+”);




                         35
DSL: lambdas II
• Oliver Steele came up with a simple set of
  rules for such language:
  • If lambda ends with an operator, it is a
    place for an implicit argument:
    • “2+”     function(x){ return 2 + x; }



                      36
DSL: lambdas III
• If lambda starts with an operator, it is a
  place for an implicit argument:
  • “+2”     function(x){ return x + 2; }

  • “+”     function(x, y){ return x + y; }

  • “/2+”     function(x, y){ return x / 2 + y; }


                       37
DSL: lambdas IV
• If lambda contains “->” it means it is a full-
  blown function:
  • “a, b -> a + b”
   • function(a, b){ return a + b; }
  • “a, b -> Math.min(a, b)”
   • function(a, b){ return Math.min(a, b); }
                       38
DSL: lambdas V
• Otherwise all different identifiers in a string
  starting with a lower-case symbol assumed
  to be arguments:
  • “x + y”     function(x, y){ return x + y; }

• Obviously all reserved words (like “this”)
  are not considered to be arguments.


                      39
DSL: lambdas VI
• dojox.lang.functional implements
  Oliver’s lambda specification.
 • They can be used consistently in any
    functions provided by this package.
 • Special compilation helpers are provided.

                     40
DSL: using lambdas I
• lambda() is a function to convert from
  lambda strings to functions.
• Let’s rewrite our example:
  var result = data.map(lambda(“x * x”)).
   filter(lambda(“x % 2 == 1”)).
   reduce(lambda(“+”));




                           41
DSL: using lambdas II
• Better, but not an ideal.
• Let’s implement functions, which can take
  either a function or a lambda string:
  var forEach = function(a, f){
   return a.forEach(typeof f == “string” ? lambda(f): f);
  };
  // and so on for other functions




                            42
DSL: using lambdas III
• Now we can reimplement the example:
  var result = map(data, “x * x”);
  result = filter(result, “x % 2 == 1”);
  result = reduce(result, “+”);

• I would say it is much better, yet chaining
  would be a better solution.
• You can do it as an exercise.
                             43
DSL: results I
• While our code is more compact and more
  readable, it takes a hit to compile a lambda.
• While the hit is relatively small, we can
  amortize it by pre-calculating a lambda:
  var f = lambda(“x * x”);
  var result = map(data, f);




                               44
DSL: results II
• Lambdas are harder to debug because we
  don’t have a direct correspondence with
  the code.
• We can mitigate it by using small concise
  expressions. (That’s the idea anyway).



                     45
Conclusion
• JavaScript has a lot of potential from the
  language point of view.
• We just opening it up for real large scale
  development.
• Over time we will see more and more non-
  browser JavaScript-based projects, and
  more complex browser-based apps.


                      46
About me
• I am an independent software developer.
• My web site:
 • http://lazutkin.com
• Follow me on Tweeter:
 • http://twitter.com/uhop

                    47

More Related Content

What's hot

4th Lecture: JSP and such
4th Lecture:  JSP and such4th Lecture:  JSP and such
4th Lecture: JSP and suchManolis Vavalis
 
Saving Time with WP-CLI
Saving Time with WP-CLISaving Time with WP-CLI
Saving Time with WP-CLITaylor Lovett
 
Simplify your integrations with Apache Camel
Simplify your integrations with Apache CamelSimplify your integrations with Apache Camel
Simplify your integrations with Apache CamelKenneth Peeples
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP PerspectiveBarry Jones
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsSadayuki Furuhashi
 
Modernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with ElasticsearchModernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with ElasticsearchTaylor Lovett
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Ngoc Dao
 
Day 9 - PostgreSQL Application Architecture
Day 9 - PostgreSQL Application ArchitectureDay 9 - PostgreSQL Application Architecture
Day 9 - PostgreSQL Application ArchitectureBarry Jones
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Best Practices for WordPress
Best Practices for WordPressBest Practices for WordPress
Best Practices for WordPressTaylor Lovett
 
You Got React.js in My PHP
You Got React.js in My PHPYou Got React.js in My PHP
You Got React.js in My PHPTaylor Lovett
 
Apache Jackrabbit Oak on MongoDB
Apache Jackrabbit Oak on MongoDBApache Jackrabbit Oak on MongoDB
Apache Jackrabbit Oak on MongoDBMongoDB
 
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...Sencha
 
Introducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applicationsIntroducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applicationsJohn Hann
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongoMax Kremer
 
MongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsMongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsSteven Francia
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Sam Muhanguzi
 

What's hot (20)

Wt unit 1 ppts web development process
Wt unit 1 ppts web development processWt unit 1 ppts web development process
Wt unit 1 ppts web development process
 
4th Lecture: JSP and such
4th Lecture:  JSP and such4th Lecture:  JSP and such
4th Lecture: JSP and such
 
Saving Time with WP-CLI
Saving Time with WP-CLISaving Time with WP-CLI
Saving Time with WP-CLI
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Simplify your integrations with Apache Camel
Simplify your integrations with Apache CamelSimplify your integrations with Apache Camel
Simplify your integrations with Apache Camel
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 
Modernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with ElasticsearchModernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with Elasticsearch
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014
 
Day 9 - PostgreSQL Application Architecture
Day 9 - PostgreSQL Application ArchitectureDay 9 - PostgreSQL Application Architecture
Day 9 - PostgreSQL Application Architecture
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Best Practices for WordPress
Best Practices for WordPressBest Practices for WordPress
Best Practices for WordPress
 
You Got React.js in My PHP
You Got React.js in My PHPYou Got React.js in My PHP
You Got React.js in My PHP
 
Apache Jackrabbit Oak on MongoDB
Apache Jackrabbit Oak on MongoDBApache Jackrabbit Oak on MongoDB
Apache Jackrabbit Oak on MongoDB
 
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
 
Introducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applicationsIntroducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applications
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongo
 
MongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsMongoDB, E-commerce and Transactions
MongoDB, E-commerce and Transactions
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1
 

Similar to JavaScript's Unique Features and How to Use Them

Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
The Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneThe Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneJames Long
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...AboutYouGmbH
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain艾鍗科技
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerGonçalo Gomes
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)lennartkats
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法x1 ichi
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS MeetupLINAGORA
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxJEEVANANTHAMG6
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark Summit
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 

Similar to JavaScript's Unique Features and How to Use Them (20)

Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
The Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneThe Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhone
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic Linker
 
Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 
[AWS Builders] Effective AWS Glue
[AWS Builders] Effective AWS Glue[AWS Builders] Effective AWS Glue
[AWS Builders] Effective AWS Glue
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
JS Essence
JS EssenceJS Essence
JS Essence
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
 
Pulsar
PulsarPulsar
Pulsar
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 

More from Eugene Lazutkin

Functional practices in JavaScript
Functional practices in JavaScriptFunctional practices in JavaScript
Functional practices in JavaScriptEugene Lazutkin
 
Express: the web server for node.js
Express: the web server for node.jsExpress: the web server for node.js
Express: the web server for node.jsEugene Lazutkin
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Eugene Lazutkin
 
SSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSSSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSEugene Lazutkin
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
Dojo GFX workshop slides
Dojo GFX workshop slidesDojo GFX workshop slides
Dojo GFX workshop slidesEugene Lazutkin
 
Dojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldDojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldEugene Lazutkin
 
DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007Eugene Lazutkin
 
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007Eugene Lazutkin
 

More from Eugene Lazutkin (17)

Service workers
Service workersService workers
Service workers
 
Advanced I/O in browser
Advanced I/O in browserAdvanced I/O in browser
Advanced I/O in browser
 
Streams
StreamsStreams
Streams
 
Functional practices in JavaScript
Functional practices in JavaScriptFunctional practices in JavaScript
Functional practices in JavaScript
 
Express: the web server for node.js
Express: the web server for node.jsExpress: the web server for node.js
Express: the web server for node.js
 
TXJS 2013 in 10 minutes
TXJS 2013 in 10 minutesTXJS 2013 in 10 minutes
TXJS 2013 in 10 minutes
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.
 
OOP in JS
OOP in JSOOP in JS
OOP in JS
 
SSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSSSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJS
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
RAD CRUD
RAD CRUDRAD CRUD
RAD CRUD
 
CRUD with Dojo
CRUD with DojoCRUD with Dojo
CRUD with Dojo
 
Dojo GFX workshop slides
Dojo GFX workshop slidesDojo GFX workshop slides
Dojo GFX workshop slides
 
Dojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldDojo GFX: SVG in the real world
Dojo GFX: SVG in the real world
 
Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)
 
DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007
 
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

JavaScript's Unique Features and How to Use Them

  • 1. Exciting JavaScript What makes it unique, how to use it. Eugene Lazutkin Dallas, TX, ClubAjax on 3/2/2010 1
  • 2. Disclaimer • I will use JavaScript, JS, and ECMAScript interchangeably. • The material is mostly based on ECMAScript 3. 2
  • 3. Why JavaScript? • Browsers. • CommonJS (ex-ServerJS) is gaining steam. • CouchDB uses it to define “views”. • Node.js with its asynchronous event-based I/O is red hot. • An explosion of JavaScript run-time environments and libraries. 3
  • 4. JS the Language I • JavaScript packages a formidable set of tools we can leverage to reduce complexity. • While it doesn’t provide a direct support for some programming paradigms, it has proper tools for us to do it. 4
  • 5. JS the Language II • Following paradigms can be supported: • Object-oriented programming (OOP). • Functional programming (FP). • Aspect-oriented programming (AOP). • Event-driven programming (EDP). • Much more. 5
  • 6. What we did last time • We look into the JavaScript-specific language facilities to see what it offers. • We dissected OOP and AOP paradigms. • We mapped simple OOP and AOP paradigms on top of available constructs. 6
  • 7. What we found • 1st-class functions. • Closures. • Hash-based extendable objects. • Duck-typing rules! • OOP can be made with a language, rather than provided by a language. 7
  • 8. Simple OOP // our constructor var Person = function(name){ // our instance-level variables this.name = name; }; // our methods and class-level variables/constants Person.prototype = { answer: 42, say: function(msg){ alert(this.name + “: “ + msg); } }; 8
  • 9. Simple AOP // augmenting Person’s say() var old = Person.prototype.say; Person.prototype.say = function(msg){ var newMsg = msg.toUpperCase(); old.call(this, newMsg); }; // WARNING: this augmentation doesn’t scale up // well, use something like dojox.lang.aop 9
  • 11. FP: short intro I • It is about representing algorithms as a composition of functions. • It stresses out the algorithmic part of programming. • It is not about states (unlike OOP), but about a control flow. 11
  • 12. FP: short intro II • Higher-order functions: • Can consume other functions as parameters. • Can return functions. • That’s where “function as a 1st-order value” pays off. 12
  • 13. FP: short intro III • Pure functions: • No side-effects. • Why? Easier to combine. • Recursion is important: • We can do it JS too. 13
  • 14. FP in JavaScript? • Some pieces of our program can be functional (e.g., stateless). • Some side-effects can be deemed “harmless for our purposes”. • They do not affect our algorithm. 14
  • 15. FP in JavaScript • Practical FP in JS: • Use adapters to customize components. • Combine components using chaining. • Convert flow statements into functions. • While jQuery is not an FP toolkit, it has popularized the style. 15
  • 16. FP: adapter example • Remember our hack with “self = this”? We can adapt our functions/methods for that: function hitch(obj, name){ return function(){ var fn = typeof name == “string” ? obj[name] : name; return fn.apply(obj, arguments); }; } 16
  • 17. FP: using hitch var queue = { stack: [], memorize: function(x){ this.stack.push(x); } }; queue.memorize(2); // or we can use it as a function with any context var q = hitch(queue, “memorize”); q(2); q(3); 17
  • 18. FP: control flow • Control flow can be implemented as higher-order functions. • Traditionally iteration and recursion are major sources of programmer’s errors. • Cut’n’paste frequently breaks internal loop variables. 18
  • 19. FP: “array extras” • Back in Firefox 1.5 so-called “array extras” were introduced: • forEach(), every(), some(), map(), filter(), indexOf(), lastIndexOf(). • Firefox 3 added: reduce(), reduceRight(). • They allow to process arrays as streams eliminating direct loops. 19
  • 20. FP: process arrays • “Array extras” allows writing very compact neatly piped data processing: var data = [...]; var result = data. map(function(x){ return x * x; }). filter(function(x){ return x % 2 == 1; }). reduce(function(a, b){ return a + b; }); 20
  • 21. More on FP • jQuery uses similar techniques on NodeList with great success. • I wrote a blog post about FP in JS and how it is implemented in Dojo: • http://lazutkin.com/blog/2008/jan/12/ functional-fun-javascript-dojo/ 21
  • 22. Inventory (cont.) Dynamic language. 22
  • 23. Code generation I • JavaScript can compile text to an executable code with two constructs: • eval() – compile a string as JavaScript. Any valid JavaScript can be compiled. • new Function() – compile a function. • We can generate code for fun and profit! 23
  • 24. Code generation II • Some environments do not allow code generation. • Sandboxes can prohibit it for security reasons. • ES5 strict mode doesn’t allow it. It works in ES5 strict mode with some caveats. • All browsers in normal mode support it. 24
  • 25. Introspection I • “for-in” loop enumerates all keys in an object. • Some keys can be hidden. • Function.toString() can return a source code for a function. • Some implementations (e.g., mobile) do not support this feature. 25
  • 26. Introspection II • Function has some additional properties like “name” or “length”. • Some browsers do not support them. • ES5 strict mode doesn’t allow inspection of “arguments.caller” and “arguments.callee”. 26
  • 27. CG advantage • Having CG around opens new vistas: • We can generate code custom-tailored (optimized) to a specific task completely on the fly. • We can use Domain-Specific Languages (DSL) to simplify our problems at hand. 27
  • 28. DSL Domain-specific languages and code generation. 28
  • 29. Implementing DSL I • DSL can be implemented in several layers: • By providing objects and libraries specific for our problem area. • Example: HTML DOM. • Example: CSS. • Example: JSON. 29
  • 30. Implementing DSL II • If our language supports it, we can provide special language constructs to make our tasks simpler: • Example: regular expressions in JavaScript. • Example: NodeList and jQuery, or dojo.query, or similar facilities of other libraries for HTML DOM and CSS. 30
  • 31. Implementing DSL III • Finally we can implement our own custom language, and interpret it, or compile it to our implementation language. • Trade-offs are easy to assess: cost of abstraction (e.g., compile time) vs. run time. 31
  • 32. HTML as DSL // let’s “program” a list var list = “ <ul> <li>Mike</li> <li>Bob</li> </ul>”; // let’s “interpret” it ourDomNode.innerHTML = list; // let’s read it back var text = ourDomNode.innerHTML; 32
  • 33. CSS as DSL // CSS selector is used in dojo.query // (all major libraries can do that nowadays) dojo.query(“.myClass li”). style({ color: “blue”, background: “yellow” }); 33
  • 34. JSON as DSL // Let’s produce some JSON var str = JSON.stringify({ answer: 42, array: [1, 2, 3, 4], subObject: {name: “Mike”} }); // old-school JSON “interpretation” // (WARNING: don’t do it at home!) var obj = eval(“(“ + str + ”)”); 34
  • 35. DSL: lambdas I • Our functional example (slide 20) was as compact as possible in JavaScript. But imagine that we had a way to reduce the functions we used? • We could have something like that: var result = data.map(“x * x”).filter(“x % 2 == 1”).reduce(“+”); 35
  • 36. DSL: lambdas II • Oliver Steele came up with a simple set of rules for such language: • If lambda ends with an operator, it is a place for an implicit argument: • “2+” function(x){ return 2 + x; } 36
  • 37. DSL: lambdas III • If lambda starts with an operator, it is a place for an implicit argument: • “+2” function(x){ return x + 2; } • “+” function(x, y){ return x + y; } • “/2+” function(x, y){ return x / 2 + y; } 37
  • 38. DSL: lambdas IV • If lambda contains “->” it means it is a full- blown function: • “a, b -> a + b” • function(a, b){ return a + b; } • “a, b -> Math.min(a, b)” • function(a, b){ return Math.min(a, b); } 38
  • 39. DSL: lambdas V • Otherwise all different identifiers in a string starting with a lower-case symbol assumed to be arguments: • “x + y” function(x, y){ return x + y; } • Obviously all reserved words (like “this”) are not considered to be arguments. 39
  • 40. DSL: lambdas VI • dojox.lang.functional implements Oliver’s lambda specification. • They can be used consistently in any functions provided by this package. • Special compilation helpers are provided. 40
  • 41. DSL: using lambdas I • lambda() is a function to convert from lambda strings to functions. • Let’s rewrite our example: var result = data.map(lambda(“x * x”)). filter(lambda(“x % 2 == 1”)). reduce(lambda(“+”)); 41
  • 42. DSL: using lambdas II • Better, but not an ideal. • Let’s implement functions, which can take either a function or a lambda string: var forEach = function(a, f){ return a.forEach(typeof f == “string” ? lambda(f): f); }; // and so on for other functions 42
  • 43. DSL: using lambdas III • Now we can reimplement the example: var result = map(data, “x * x”); result = filter(result, “x % 2 == 1”); result = reduce(result, “+”); • I would say it is much better, yet chaining would be a better solution. • You can do it as an exercise. 43
  • 44. DSL: results I • While our code is more compact and more readable, it takes a hit to compile a lambda. • While the hit is relatively small, we can amortize it by pre-calculating a lambda: var f = lambda(“x * x”); var result = map(data, f); 44
  • 45. DSL: results II • Lambdas are harder to debug because we don’t have a direct correspondence with the code. • We can mitigate it by using small concise expressions. (That’s the idea anyway). 45
  • 46. Conclusion • JavaScript has a lot of potential from the language point of view. • We just opening it up for real large scale development. • Over time we will see more and more non- browser JavaScript-based projects, and more complex browser-based apps. 46
  • 47. About me • I am an independent software developer. • My web site: • http://lazutkin.com • Follow me on Tweeter: • http://twitter.com/uhop 47

Editor's Notes