SlideShare a Scribd company logo
JavaScript Growing Up
 Modules, Platform Consistency and Harmony




              David Padbury
Between HTML5 and Node, JavaScript
is seeing a staggering level of adoption.
The patterns and tools and practices that will form
 the foundation of Modern JavaScript are going to
have to come from outside implementations of the
                  language itself
                                       - Rebecca Murphey
Modules
Java has import


C# has using


 JavaScript has?
    Nothing.
So JavaScript authors used what we had in
the language to provide what we needed.
But before we get to that,
 first some prerequisites.
Everything is global


// lib1.js
var name = 'Barry';

function sayHi() {
    alert("Hi, I'm " + name);
}

<script src="lib1.js"></script>
<script>
    something();
    console.log(name); // Barry
</script>
Which could make including multiple libraries challenging

         // lib1.js
         function something() {
             console.log('foo');
         }

         // lib2.js
         function something() {
             console.log('bar');
         }

         <script src="lib1.js"></script>
         <script src="lib2.js"></script>
         <script>
             something();
         </script>
Using simple JavaScript constructs we can emulate many
          traditional organization techniques

     ;(function(lib1) {

          lib1.something = function() {
              ...
          };

     })(window.lib1 = window.lib1 || {});

     lib1.something();
     lib2.something();
function namespace(ns) {
    var obj = window;

    ns.split('.').forEach(function(component) {
        obj = typeof obj[component] !== 'undefined'
            ? obj[component]
            : obj[component] = {};
    });

    return obj;
}
(function(data) {
    data.something = function() {
        ...
    };
})(namespace('lab49.app.data'));
(function(example) {

   function privateAdd(num1, num2) {
       return num1 + num2;
   }

   example.add = function(num1, num2) {
       return privateAdd(num1, num2);
   };

})(namespace('lab49.example'));



console.log(typeof example.add); // function
console.log(typeof example.privateAdd); // undefined
console.log(typeof privateAdd); // undefined
Server-side JavaScript authors started to talk about
what a more robust module system would look like.
I generally support the CommonJS idea, but let’s
be clear: it’s hardly a specification handed down by
the gods (like ES5); it’s just some people discussing
  ideas on a mailing list. Most of these ideas are
          without actual implementations.
                                   - Ryan Dahl (creator of node.js)
Introduced a simple API for dealing with modules.

       require for importing a module.

  exports for exposing stuff from a module.




             http://wiki.commonjs.org/wiki/Modules/1.1.1
// math.js
exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
        sum += args[i++];
    }
    return sum;
};

//increment.js
var add = require('math').add;
exports.increment = function(val) {
    return add(val, 1);
};

// program.js
var inc = require('increment').increment;
var a = 1;
inc(a); // 2
CommonJS modules are now the de-facto
    for server based JavaScript.
var http = require('http');

var server = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hi Lab!');
});
There are now a number of tools to bring
  CommonJS modules to the browser.

         https://github.com/substack/node-browserify


             https://github.com/sstephenson/stitch
var stitch = require('stitch');
var express = require('express');

var package = stitch.createPackage({
  paths: [__dirname + '/lib', __dirname + '/vendor']
});

var app = express.createServer();
app.get('/application.js', package.createServer());
app.listen(3000);
There are some problems with using this
    module format in the browser.
Asynchronous Module Definition
  (Commonly known as AMD)




    https://github.com/amdjs/amdjs-api/wiki/AMD
define for creating a module definition.
define('personView', ['models/person'], function(person) {
    return {
        initialize: function() {
            ...
        }
    };
});
AMD is now used by RequireJS, Dojo and even Node.
RequireJS also supports text templates.
Becoming the most common way to structure large JavaScript
    applications, both on the server and in the browser.
JS.next will be introducing language level modules.
These are similar to the modules we’ve been looking at.
module Math {
    export function add(x, y) {
        return x + y;
    }
}

Math.add(2, 2);

import Math.*;
add(2,2);
But not much implements that yet.

        Why do we care?
       I’ll get to that later.
Platform Consistency
Everyone knows that the biggest suckage in modern
    JavaScript is dealing with different platforms.
Polyfill

A shim that mimics a future API, providing
 fallback functionality to older browsers.




            http://stateofhtml5.appspot.com/
You can fake a surprising amount now days.
;(function(geolocation){

  if (geolocation) return;

  var cache;

 geolocation = window.navigator.geolocation = {};
 geolocation.getCurrentPosition = function(callback){

      if (cache) callback(cache);

      $.getScript('//www.google.com/jsapi',function(){

       cache = {
         coords : {
           "latitude": google.loader.ClientLocation.latitude,
           "longitude": google.loader.ClientLocation.longitude
         }
       };

     callback(cache);
   });

 };

 geolocation.watchPosition = geolocation.getCurrentPosition;

})(navigator.geolocation);
border-radius: 8px;
box-shadow: #666 0px 2px 3px;
background: linear-gradient(#eeff99, #66ee33);
behavior: url(/PIE.htc);




                   http://css3pie.com/
But just because you can,
it doesn’t mean that you should.
But if we are in different environments,
we can start with some polyfills that are much simpler.
Array.prototype.forEach
Array.prototype.map
Array.prototype.filter
Array.prototype.every
Array.prototype.some
Array.prototype.reduce
Array.prototype.indexOf
Object.keys
Date.now
Date.prototype.toISOString
Function.prototype.bind
String.prototype.trim
['one', 'two', 'three'].map(function(word) {
    return word.length
}).filter(function(length) {
    return length > 3;
});
It is not seldom that you see people messing with
Object.prototype.This is very bad because it breaks the
        object-as-hash-tables feature in javascript.
  Array.prototype.map = function() {...};

  var arr = [1,2,3];

  for (var p in arr) {
      console.log(p);
  }

  //     1
  //     2
  //     3
  //     map - erm, what?
http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/
Array.prototype.map = function() {...};

var arr = [1,2,3];

for (var p in arr) {
    if (arr.hasOwnProperty(p)) {
        console.log(p);
    }
}
So where we can polyfill basic language functionality,
              take advantage of it.




                https://github.com/kriskowal/es5-shim
Harmony
JavaScript Growing Up
JavaScript is the x86 of the web
     - Brendan Eich (creator of JavaScript)
Google Traceur - JavaScript to JavaScript Compiler




              http://code.google.com/p/traceur-compiler/
Harmony Features
                      Modules
                      Iterators
               Iterators and For Each
                     Generators
               Block Scoped Bindings
              Destructuring Assignment
                 Default Parameters
                  Rest Parameters
                  Spread Operator

             Strawman Features
                       Classes
                         Traits
                Deferred Functions
             Object Initializer Shorthand



http://code.google.com/p/traceur-compiler/wiki/LanguageFeatures
Destructuring Assignment




var [a, [b], c] = ['hello', [', ', 'junk'], 'world'];
alert(a + b + c); // hello, world
              http://traceur-testbed.herokuapp.com/destructuringArrayAssignment




                       var pt = {
                          x: 23,
                          y: 42
                       };

                       var {x, y} = pt;

                       console.log(x); // 23
             http://traceur-testbed.herokuapp.com/destructuringObjectAssignment
function slice(list, start = 0, end = list.length) {
    ...
}
               http://traceur-testbed.herokuapp.com/defaultParameters
function print(...items) {
    items.forEach(function(item, index) {
        console.log(index, item);
    });
}

print('foo', 'bar');
// 0, foo
// 1, bar
           http://traceur-testbed.herokuapp.com/restParameters
var a1 = [1,2,3],
    a2 = [];

a2.push(...a1);

// a1.push.apply(a1, a2)

 http://traceur-testbed.herokuapp.com/spreadOperator
Deferred / Promises

var deferred = $.Deferred();
// or dojo.Deferred, new Deferred(), etc...

// Complete the deferred
deferred.resolve(...args);

// Fail the deferred
deferred.reject(...args);

// Return a read-only deferred
deferred.promise();

// Attach handlers for when resolve or rejected
deferred.then(function(...args) { ... }, function(...args) {...});



                       http://wiki.commonjs.org/wiki/Promises
function wait(duration) {
    var deferred = $.Deferred();

    window.setTimeout(function() {
        deferred.resolve();
    });

    return deferred.promise();
}

wait(1000).then(function() {
    alert('done');
});
function deferredWait(timeout) {
    var d = $.Deferred();

    window.setTimeout(function() {
        d.resolve();
    }, timeout);

    return d;
}

function waitOnThings() {
    alert('Starting');
    await deferredWait(1000);
    alert('Finished');
}

        http://traceur-testbed.herokuapp.com/await
Thanks for listening!

More Related Content

What's hot

ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Computer science Investigatory Project Class 12 C++
Computer science Investigatory Project Class 12 C++Computer science Investigatory Project Class 12 C++
Computer science Investigatory Project Class 12 C++
Rushil Aggarwal
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
JavaScript
JavaScriptJavaScript
Rust-lang
Rust-langRust-lang
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
Tiji Thomas
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
Ross Tuck
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 

What's hot (20)

ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Files in php
Files in phpFiles in php
Files in php
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Computer science Investigatory Project Class 12 C++
Computer science Investigatory Project Class 12 C++Computer science Investigatory Project Class 12 C++
Computer science Investigatory Project Class 12 C++
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Javascript
JavascriptJavascript
Javascript
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 

Viewers also liked

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
Stoyan Stefanov
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Updated: NW.js - Desktop Apps with Javascript
Updated: NW.js - Desktop Apps with JavascriptUpdated: NW.js - Desktop Apps with Javascript
Updated: NW.js - Desktop Apps with Javascript
Ralf Schwoebel
 
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
Yahoo Developer Network
 
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
Yahoo Developer Network
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation
 
August 2016 HUG: Recent development in Apache Oozie
August 2016 HUG: Recent development in Apache OozieAugust 2016 HUG: Recent development in Apache Oozie
August 2016 HUG: Recent development in Apache Oozie
Yahoo Developer Network
 

Viewers also liked (7)

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Updated: NW.js - Desktop Apps with Javascript
Updated: NW.js - Desktop Apps with JavascriptUpdated: NW.js - Desktop Apps with Javascript
Updated: NW.js - Desktop Apps with Javascript
 
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
August 2016 HUG: Open Source Big Data Ingest with StreamSets Data Collector
 
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
August 2016 HUG: Better together: Fast Data with Apache Spark™ and Apache Ign...
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
August 2016 HUG: Recent development in Apache Oozie
August 2016 HUG: Recent development in Apache OozieAugust 2016 HUG: Recent development in Apache Oozie
August 2016 HUG: Recent development in Apache Oozie
 

Similar to JavaScript Growing Up

How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
jbandi
 
Play framework
Play frameworkPlay framework
Play framework
Andrew Skiba
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
elliando dias
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
Skills Matter
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 

Similar to JavaScript Growing Up (20)

How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
Play framework
Play frameworkPlay framework
Play framework
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 

Recently uploaded

find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
Ivanti
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
Priyanka Aash
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes..."Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
Anant Gupta
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Torry Harris
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
Figma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdfFigma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdf
Management Institute of Skills Development
 
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
digitalxplive
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
Safe Software
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 

Recently uploaded (20)

find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes..."Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
Figma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdfFigma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdf
 
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
The Rise of AI in Cybersecurity How Machine Learning Will Shape Threat Detect...
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 

JavaScript Growing Up

  • 1. JavaScript Growing Up Modules, Platform Consistency and Harmony David Padbury
  • 2. Between HTML5 and Node, JavaScript is seeing a staggering level of adoption.
  • 3. The patterns and tools and practices that will form the foundation of Modern JavaScript are going to have to come from outside implementations of the language itself - Rebecca Murphey
  • 5. Java has import C# has using JavaScript has? Nothing.
  • 6. So JavaScript authors used what we had in the language to provide what we needed.
  • 7. But before we get to that, first some prerequisites.
  • 8. Everything is global // lib1.js var name = 'Barry'; function sayHi() { alert("Hi, I'm " + name); } <script src="lib1.js"></script> <script> something(); console.log(name); // Barry </script>
  • 9. Which could make including multiple libraries challenging // lib1.js function something() { console.log('foo'); } // lib2.js function something() { console.log('bar'); } <script src="lib1.js"></script> <script src="lib2.js"></script> <script> something(); </script>
  • 10. Using simple JavaScript constructs we can emulate many traditional organization techniques ;(function(lib1) { lib1.something = function() { ... }; })(window.lib1 = window.lib1 || {}); lib1.something(); lib2.something();
  • 11. function namespace(ns) { var obj = window; ns.split('.').forEach(function(component) { obj = typeof obj[component] !== 'undefined' ? obj[component] : obj[component] = {}; }); return obj; }
  • 12. (function(data) { data.something = function() { ... }; })(namespace('lab49.app.data'));
  • 13. (function(example) { function privateAdd(num1, num2) { return num1 + num2; } example.add = function(num1, num2) { return privateAdd(num1, num2); }; })(namespace('lab49.example')); console.log(typeof example.add); // function console.log(typeof example.privateAdd); // undefined console.log(typeof privateAdd); // undefined
  • 14. Server-side JavaScript authors started to talk about what a more robust module system would look like.
  • 15. I generally support the CommonJS idea, but let’s be clear: it’s hardly a specification handed down by the gods (like ES5); it’s just some people discussing ideas on a mailing list. Most of these ideas are without actual implementations. - Ryan Dahl (creator of node.js)
  • 16. Introduced a simple API for dealing with modules. require for importing a module. exports for exposing stuff from a module. http://wiki.commonjs.org/wiki/Modules/1.1.1
  • 17. // math.js exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; }; //increment.js var add = require('math').add; exports.increment = function(val) { return add(val, 1); }; // program.js var inc = require('increment').increment; var a = 1; inc(a); // 2
  • 18. CommonJS modules are now the de-facto for server based JavaScript.
  • 19. var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hi Lab!'); });
  • 20. There are now a number of tools to bring CommonJS modules to the browser. https://github.com/substack/node-browserify https://github.com/sstephenson/stitch
  • 21. var stitch = require('stitch'); var express = require('express'); var package = stitch.createPackage({ paths: [__dirname + '/lib', __dirname + '/vendor'] }); var app = express.createServer(); app.get('/application.js', package.createServer()); app.listen(3000);
  • 22. There are some problems with using this module format in the browser.
  • 23. Asynchronous Module Definition (Commonly known as AMD) https://github.com/amdjs/amdjs-api/wiki/AMD
  • 24. define for creating a module definition.
  • 25. define('personView', ['models/person'], function(person) { return { initialize: function() { ... } }; });
  • 26. AMD is now used by RequireJS, Dojo and even Node.
  • 27. RequireJS also supports text templates.
  • 28. Becoming the most common way to structure large JavaScript applications, both on the server and in the browser.
  • 29. JS.next will be introducing language level modules. These are similar to the modules we’ve been looking at.
  • 30. module Math { export function add(x, y) { return x + y; } } Math.add(2, 2); import Math.*; add(2,2);
  • 31. But not much implements that yet. Why do we care? I’ll get to that later.
  • 33. Everyone knows that the biggest suckage in modern JavaScript is dealing with different platforms.
  • 34. Polyfill A shim that mimics a future API, providing fallback functionality to older browsers. http://stateofhtml5.appspot.com/
  • 35. You can fake a surprising amount now days.
  • 36. ;(function(geolocation){ if (geolocation) return; var cache; geolocation = window.navigator.geolocation = {}; geolocation.getCurrentPosition = function(callback){ if (cache) callback(cache); $.getScript('//www.google.com/jsapi',function(){ cache = { coords : { "latitude": google.loader.ClientLocation.latitude, "longitude": google.loader.ClientLocation.longitude } }; callback(cache); }); }; geolocation.watchPosition = geolocation.getCurrentPosition; })(navigator.geolocation);
  • 37. border-radius: 8px; box-shadow: #666 0px 2px 3px; background: linear-gradient(#eeff99, #66ee33); behavior: url(/PIE.htc); http://css3pie.com/
  • 38. But just because you can, it doesn’t mean that you should.
  • 39. But if we are in different environments, we can start with some polyfills that are much simpler.
  • 41. ['one', 'two', 'three'].map(function(word) { return word.length }).filter(function(length) { return length > 3; });
  • 42. It is not seldom that you see people messing with Object.prototype.This is very bad because it breaks the object-as-hash-tables feature in javascript. Array.prototype.map = function() {...}; var arr = [1,2,3]; for (var p in arr) { console.log(p); } // 1 // 2 // 3 // map - erm, what? http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/
  • 43. Array.prototype.map = function() {...}; var arr = [1,2,3]; for (var p in arr) { if (arr.hasOwnProperty(p)) { console.log(p); } }
  • 44. So where we can polyfill basic language functionality, take advantage of it. https://github.com/kriskowal/es5-shim
  • 47. JavaScript is the x86 of the web - Brendan Eich (creator of JavaScript)
  • 48. Google Traceur - JavaScript to JavaScript Compiler http://code.google.com/p/traceur-compiler/
  • 49. Harmony Features Modules Iterators Iterators and For Each Generators Block Scoped Bindings Destructuring Assignment Default Parameters Rest Parameters Spread Operator Strawman Features Classes Traits Deferred Functions Object Initializer Shorthand http://code.google.com/p/traceur-compiler/wiki/LanguageFeatures
  • 50. Destructuring Assignment var [a, [b], c] = ['hello', [', ', 'junk'], 'world']; alert(a + b + c); // hello, world http://traceur-testbed.herokuapp.com/destructuringArrayAssignment var pt = { x: 23, y: 42 }; var {x, y} = pt; console.log(x); // 23 http://traceur-testbed.herokuapp.com/destructuringObjectAssignment
  • 51. function slice(list, start = 0, end = list.length) { ... } http://traceur-testbed.herokuapp.com/defaultParameters
  • 52. function print(...items) { items.forEach(function(item, index) { console.log(index, item); }); } print('foo', 'bar'); // 0, foo // 1, bar http://traceur-testbed.herokuapp.com/restParameters
  • 53. var a1 = [1,2,3], a2 = []; a2.push(...a1); // a1.push.apply(a1, a2) http://traceur-testbed.herokuapp.com/spreadOperator
  • 54. Deferred / Promises var deferred = $.Deferred(); // or dojo.Deferred, new Deferred(), etc... // Complete the deferred deferred.resolve(...args); // Fail the deferred deferred.reject(...args); // Return a read-only deferred deferred.promise(); // Attach handlers for when resolve or rejected deferred.then(function(...args) { ... }, function(...args) {...}); http://wiki.commonjs.org/wiki/Promises
  • 55. function wait(duration) { var deferred = $.Deferred(); window.setTimeout(function() { deferred.resolve(); }); return deferred.promise(); } wait(1000).then(function() { alert('done'); });
  • 56. function deferredWait(timeout) { var d = $.Deferred(); window.setTimeout(function() { d.resolve(); }, timeout); return d; } function waitOnThings() { alert('Starting'); await deferredWait(1000); alert('Finished'); } http://traceur-testbed.herokuapp.com/await

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n