Past, present and – future of JavaScript – Moritz Grauel



Past, present and – future of JavaScript – Moritz Grauel

0 0


zbtn-2014-02

Slides from my Zaunberg Tech Night Talk

On Github mo-gr / zbtn-2014-02

Past, present and

future of JavaScript

Moritz Grauel

Moritz Grauel

Berlin native. Bit herder. Code connoisseur. Coffee lover.

@mo_gr

mo@notadomain.com

http://moritz.grauel.is/awesome

Freelance Software Developer and Trainer

software professional > 7 years

JVM based web applications

strong frontend focus

some iOS

JavaScript

a little bit of history

the year was 1995

browser wars between Microsoft and Netscape

Brendan Eich

  • asked to create a scripting language for Netscape Navigator
  • strong influence by scheme and self
  • promising project

middle management

forced Java-like Syntax

forced confusing Java name

extreme time pressure

browser wars → copy wars

IE copied JavaScript within 1 year

JScript

Standards

in 1997 JavaScript became ECMA Script

adopted by all browser manufacturers

consistend behaviour in browsers

does not directly cover the DOM API

DOM API

source of pain in old browsers

very different interpretation

inconsistent API

wrong implementations

...more on that later

Douglas Crockford

  • most famous for JSON
  • 2008: released a book

JavaScript: The good parts

He stared JavaScript into the eye

JSLint vs. JSHint

JavaScripts intended purpose

simple DOM manipulations

reacting to user input

simple glue code

Cross Browser

getting it to work consistent in Mozilla and IE was a pain

...but

scripts were simple

all was good

until...

AJAX

introduced around 2000

by Microsoft for Outlook Web Access

XMLHttpRequest standardized by W3C in 2006

People started building more and more complex things in JavaScript

even simple things are hard to do correct

// attaching an eventlistener
if (elem.addEventListener) {
    elem.addEventListener(event, callbackFn, false);
} else {
    elem.attachEvent("on" + event, callbackFn);
}

Library spring

libraries to abstract cross browser quirks away popped up everywhere

They usually provided uniform event handling, AJAX facilities and some basic animation support

jQuery, Mootools, YUI, Scriptaculous, Prototype and many more

jQuery

most successfull

initial release 2006

  • browser quirks
  • DOM manipulation
  • event handling
  • AJAX calls
  • animations

taught a lot of devs about CSS selectors

painless

$(elem).on('click', callbackFn);

hand crafted

very imperative approach

no architectural support

Common approach

manually attach event handlers

manually mangle DOM with AJAX results

spaghetti-callback code

  $('#actionButton').on('click', function() {
    var data = collectAndValidateUserInput();
    $.ajax(
      type: 'POST',
      data: data,
      success: function(response) {
        $('#outputArea').html(prepareOutputFromResponse(response));
      }
    );
  });
        

Is this good code?

How do you test this?

Seperation of concerns?

Reuse?

state? DOM? JS?

This style is not inherently bad

widely in use

sucessfull

requires discipline

Is this the only way to write JavaScript applications?

There are worse ways

Abstracting it all away

GWT, JSF et. al.

very leaky abstractions

usually crappy UI/UX

too little control

There are better ways

embrace it and stop hacking around

treat it as a first class citizen of your technology stack

apply some architecture and software engineering best practices

JavaScript today

JavaScript engines

no more compatibility problems

very fast

highly sophisticated

node.js

Chromes engine V8 w/o the Browser

released 2009

foundation for many great tools

we are not creating interactive web sites anymore

we create graphical user interfaces for distributed applications

creating GUIs is not a new thing

Common Approach

some variation of Model-View-Controller

smalltalk did this in the 70ies

Model-View-Whatever

different MVC interpretations

Model View Controller

Model View View-Model

Model View Presenter

MVC in JavaScript

dozens of frameworks

similar situation to jQuery-like libraries a few years ago

a new one popping up every few minutes

They usually provide

  • architectural structure
  • some form of components or modules
  • some form of server sync
  • a lot of the common glue code
  • far less imperative code

TodoMVC

  • good overview of popular frameworks
  • reference implementation of a todo app
  • great for comparison and to get started

The big ones

  • AngularJS
  • Backbone.js
  • Ember.js
  • [your personal favorite]

hopefully convinces you about MVC instead of manually weaving

events into applications

AngularJS

Superheroic JavaScript MVW Framework

innovative approaches to web dev

Some facts

Open Source (MIT), developed at Google

first release 2009

currently 1.2.13

~99kB minified

over 400 contributors

Igor Minar

Miško Hevery

AngularJS' main features

  • 2-way data binding
  • templating
  • modularity
  • testability
  • dependency injection

AngularJS' focus

  • client only
  • no UI components
  • be extensible and modular
  • provide structure and framework
  • provide common functionality (templating, AJAX, form handling etc)

MVC in AngularJS

  • Model: regular JS objects
  • View: HTML++ (templates + directives)
  • Controller: glue between V & Services
  • Services: place for business logic, AJAX and so on

Directives

flexible extensions to HTML

attributes, tags, classes and comments

DOM interactions should (usually) all be directives

important concepts

  • model, view & controller
  • scope
  • directives
  • service

enough talk, show me code!

Final example

enough for now...

we are only just scratching the surface of what angular can do

want to learn more? ask me later!

AngularJS and jQuery?

AngularJS uses jQuery if it is available

falls back to jQLite otherwise

common recommendation: start w/o jQuery to avoid falling back into old habbits

The Future?

Future of AngularJS

Near future

Version 1.3 expected in a few weeks

drops IE8 support (and so should you)

removes deprecated features

Long term

AngularJS might be a bridge technology

Google is pushing hard in that direction

databinding → Object.observe

directives → WebComponents

Polymer

modularity → ECMA Script 6

dependeny injection → simple library?

...looong way

AngularDart

Future of JavaScript

Compile to JS languages?

Two variants

custom runtime language sugar

Custom Runtime

Dart, ClojureScript, etc.

real improvement

heavy (performance and learning curve)

Language Sugar

CoffeeScript, TypeScript, Sweet.js, etc.

can improve developer-happyness

usually minor improvements over JavaScript

require knowledge of JavaScript

Compile to JS languages

no silver bullet

user, where appropriate

won't replace JavaScript

source maps are finally here (except in IE)

Web Assembler?

JavaScript Engines are already very fast

JavaScript is now an LLVM target

asm.js - highly optimizable subset of JS

intended as a compilation target

JavaScript.next?

JavaScript is here to stay

don't expect a new language to show up

consense is highly unlikely

better get used to it

Get used to it

ECMA Script 6 (Harmony)

beta feature in most browsers

first real improvements in 5 years

modules, real maps/sets, syntax cleanup

Harmony samples

        const FOO = 'foo';
        let blockScoped = '\o/';
        var [a, b] = [b, a];
        for (i of aThing) { ... }
        (aParam) => { return aParam * 2 }
        

JavaScript might evolve into a nice language

Browser situation

a lot better

standardization and auto-updates

far less need for jQuery

even IE10 is a nice browser

It's a great time to be a web developer

Summary

stop hating JS - it had a rough childhood

treat the web page as a proper UI - use some Model-View-Whatever

JS turns into a nice language - still unsatisfied? compile to it

Questions?

One more thing...

React.js

View technology (no M, no C)

developed at facebook

very interesting concepts

Disclaimer

I have nearly no experience in react.js

following might contain errors

don't confuse with react.js

React.js in a nutshell

always render the whole app

widgets render based on current state

utilizes requestAnimationFrame

isn't rendering the whole app everytime slow?

Virtual DOM

render the whole app to a virtual DOM

diff the virtual DOM with previous frame

only apply necessary changes to real DOM

Advantages

updates to the model cause DOM change for free

clear architecture

virtual dom also works on the server

SPA can be delivered with initial DOM generated on server

var Timer = React.createClass({
  getInitialState: function() {
    return {secondsElapsed: 0};
    },
  tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  componentDidMount: function() {
    this.interval = setInterval(this.tick, 1000);
  },
  render: function() {
    return (
      React.DOM.div(null, "Seconds Elapsed: ", this.state.secondsElapsed)
    );
  }
});

React.js

might not be The Next Big Thing™

great concept, likely to become more mainstream in one form or another

different enough to be worth checking out

much love in Function Programming circles

Thank you very much!