JavaScript – Crash Course – The Golden Age of JavaScript



JavaScript – Crash Course – The Golden Age of JavaScript

0 1


js-crash-course

JavaScript Crash Course

On Github kenkunz / js-crash-course

JavaScript

Crash Course

Ken Kunz / @kennethkunz

Instructions

  • Advance through major sections using right-arrow
  • Advance within a section using down-arrow
  • Hit escape to see a slide overview
  • For code examples with Run option, open the browser console to see output.
  • Edit the code right in the browser and re-run it!

How JavaScript

Launched

My Career

Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).

The Golden Age of JavaScript

We are in the Golden Age of JavaScript. When historians look back on crazy, amazing era of explosive innovation in web and mobile technologies and consider: "what was the single most important programming language in use at the time" – there will be little debate that it was JavaScript.

JavaScript is Everywhere

  • Web Browser
  • Desktop (browser, command line)
  • Mobile Phone (browser!)
  • Mobile Apps (UIWebView)
  • node.js, spidermonkey, Rhino, …
  • Hardware (tessel.io)
  • Minecraft (LearnToMod, ScriptCraft)

Are you convinced yet?

JavaScript is Fast

Source: Alex's blog › Javascript vs Perl vs Python vs Lua speed comparison

JavaScript is the

Assembly Language of the Web

JavaScript has solid tooling

  • Firebug
  • Web inspectors/debuggers
  • jslint / jshint
  • Editor / IDE support

JavaScript has a

mature

lib/framework ecosystem

This is ratherunexpected!

Some Boring Stuff

JavaScript Language

  • Interpreted
  • C-style syntax
  • Dynamic Typing
  • Object-Oriented
  • Prototype-based
  • First-Class Functions
  • Single-Threaded

Multi-Paradigm

Supports object-oriented, imperative and functional programming styles.

JavaScript Basics

Hello World

              console.log('Hello, world!');
            
Run

Types

  • Numbers
  • Strings
  • Booleans
  • Objects
  • Arrays
  • Functions
  • Regular Expressions

Numbers

// these are all number literals
console.log( 1, 1.23, 1.2e4, 1.2e-4, 0377, 0xFF );

// here are some other interesting numbers
console.log( 0/1 , 1/0, -1/0, 0/0 );

// they're all numbers
console.log(typeof 1, typeof Infinity, typeof NaN);
            
Run

Strings

var s = "foo";

console.log( s.length );
console.log( s.toUpperCase() );
console.log( s[1], s.charAt(1), s.charCodeAt(1) );
console.log( s + "bar" );

var s2 = s.replace("oo", "owl");
console.log( s, s2 );

console.log( typeof s );
            
Run

Booleans

console.log( true, false );

console.log( true && false );
console.log( true || false );
console.log( !true );
console.log( 0 === 0, 0 !== 0 );

console.log( typeof true, typeof false );

// note: all of these evaluate to false:
false, 0, "", null, undefined;
            
Run

Objects

var o = {
  foo: "abc",
  bar: 1,
  baz: { a: "bingo", b: "flamingo" }
}

console.log( o.foo );
console.log( o["bar"] );
console.log( o.baz.a );

var key = "bar";
console.log( o[key] );
            
Run

JSON = JavaScript Object Notation

Arrays

var a = [1, 2, 3, "foo"];
var b = Array(100);

console.log( a.length, b.length );

a[20] = "twenty";

console.log( a.length, a[20], a[19] );
console.log( Object.keys(a) );

console.log( typeof a );
            
Run

Functions

function randomInt(max) {
  var random = Math.random() * max;
  var randomInt = Math.round(random);
  return randomInt;
}

console.log( randomInt(100) );
console.log( randomInt(1000) );
            
Run

Control Structures

  • variables / scoping
  • conditionals
  • switch / case
  • while / do…while
  • for / for in
  • try / catch / finally

Variables / Scoping (p1)

var foo = 'foo',
    bar = [ 1, 2, 3 ],
    baz;

console.log( foo, bar, baz );

if (true) {
  var foo = 1;
}

// console.log(foo);
            
Run

Variables / Scoping (p2)

var foo = 'foo';

function bar() {
  var foo = 'bar';
  return foo;
}

console.log( bar() );
console.log( foo );
            
Run

Variables / Scoping (p3)

var foo, bar;

function foobar() {
  foo = 'foo';
  var bar = 'bar';
}

foobar();

console.log( foo, bar );
            
Run

Always declare your variables with var !!!

Conditionals

var a = 0.1,
    b = 0.2,
    c = 0.3;

if (a + b === c) {
  console.log('JavaScript does good maths!');
} else if (a * 2 === b) {
  console.log('at least sometimes!');
} else {
  console.log('wtf?');
}
            
Run

Switch / Case

var fav = prompt("What's your favorite color?");

switch (fav.toLowerCase()) {
  case "blue":
    console.log("mine too!");
    break;
  case "green":
    console.log("it's not easy being green...");
    break;
  default:
    console.log("how nice");
}
            
Run

(often an anti-pattern)

While / Do While

var list = [1, 2, 3, 4, 5];
var item;

while (item = list.pop()) {
  console.log(item);
}

// this will run at least once
do {
  console.log('length:', list.length);
} while (list.length);
            
Run

For Loop

var list = ["one", "two", "three", "four", "five"];

// just like C
for ( var idx = 0 ; idx < list.length ; idx++ ) {
  console.log( list[idx] );
}
            
Run

For-In Loop

var person = {
  name: 'Ken',
  title: 'Director of Product Development',
  favoriteMovie: 'District 9'
}

for (key in person) {
  console.log( key, ":", person[key] );
}

// note: no guaranteed ordering
            
Run

Try / Catch / Finally

// ... temporarily redefine console.log
var _originalLog = console.log;
console.log = function(val) { _originalLog("EVAL LOG: " + val); }

var code = 'foo bar baz';

try {
  eval(code);
} catch(e) {
  console.error('EVAL ERROR: ' + e.toString());
} finally {
  console.log = _originalLog;
}
            
Run

Prototypical Inheritance

We're not in Kansas Classical Inheritance land anymore

Functions are Constructors!

// _any_ function can be used as a constructor

function foo() {
  return 'foo';
}

// use the 'new' operator to construct an object
var f = new foo();

console.log( f.constructor );

console.log( f.__proto__ === foo.prototype );
            
Run

Constructor Functions…

function Shape(id) {
  this.id = id;
}
Shape.prototype.shapeName = 'Generic Shape';
Shape.prototype.inspect = function() {
  return this.shapeName + " (" + this.id + ")";
}

var shape = new Shape(123);
console.log( shape.inspect() );
            
Run

Prototype Inheritance Chain

function Shape(id) {
  this.id = id;
}
Shape.prototype.shapeName = 'Generic Shape';
Shape.prototype.inspect = function() {
  return this.shapeName + " (" + this.id + ")";
}

function Rectangle(width, length) {
  this.width = width;
  this.length = length;
  this.id = width + 'x' + length;
}
Rectangle.prototype = new Shape();
Rectangle.prototype.shapeName = 'Rectangle';
Rectangle.prototype.area = function() {
  return this.width * this.length;
}
            
Run

EcmaScript 6

  • aka, ES6, ES2015, Harmony or ES.next
  • ratified in June 2015
  • …so can I start using it??!?

ES6 Compatibility

Block Scope

let foo = 'foo';

if (true) {
  let foo = "bar";
  console.log(foo);
}

for (let foo=1; foo<2; foo++) { console.log(foo); }

console.log(foo);
            
Run

Always declare your variables with var const or let !!!

(Fat) Arrows

var a = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
];

// old way
a.map(function(s){ return s.length });

// new way
a.map( s => s.length );
            
Run

Lexical This

function Foo() {
  this.val = 10;

  setTimeout(function() { console.log(this.val); }, 100);

  setTimeout(() => console.log(this.val), 200);
}

new Foo();
            
Run

Classes

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get name() {
    return this.firstName + " " + this.lastName;
  }

  set name(name) {
    var names = name.split(" ");
    this.firstName = names[0];
    this.lastName = names[1];
  }
}
            
Run

Other Features

// default arguments
var hello = function(name = "guest") {
  console.log(name);
}

// destructuring assignment
[ first, , last ] = [ 1, 2, 3, 4, 5 ];
            
Run

And More!

  • Modules
  • Promises
  • Iterators
  • Generators
  • Unicode
  • Tail Call Optimization

Client-Side JavaScript

How the IE6 DOM almost killed my soul

jQuery

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

$("#awesome")

jQuery

DOM Traversal and Manipulation

              $( "button.continue" ).html( "Next Step..." )
            

jQuery

Event Handling

var hiddenBox = $( "#banner-message" );
$( "#button-container button" ).on( "click", function( event ) {
  hiddenBox.show();
});
            

jQuery

Ajax

$.ajax({
  url: "/api/getWeather",
  data: {
    zipcode: 97201
  },
  success: function( data ) {
    $( "#weather-temp" ).html( "" + data + " degrees" );
  }
});
            

Front-end frameworks

  • Angular.js (Google)
  • Ember.js
  • Backbone.js
  • React.js / Flux

Server-Side JavaScript

Resources

JavaScript Crash Course Ken Kunz / @kennethkunz