JavaScript Fundamentals



JavaScript Fundamentals

0 0


fundamentals-of-javascript-slides

"Mastering the Fundamentals of JavaScript" slides for MobileWebDevConference

On Github jsantell / fundamentals-of-javascript-slides

JavaScript Fundamentals

Jordan Santell / @jsantell

Slides

http://github.com/jsantell/fundamentals-of-javascript-slides

History of JavaScript

  • Made in 10 days in May 1995 by Brendan Eich of Netscape
  • Mocha -> LiveScript -> JavaScript
  • Taken to ECMA for standardization

ECMAScript

  • ECMA-262 Ed. 1 ECMAScript in 1996/1997
  • ES3 in 1999, modern JS
  • ES4 RIP
  • ES5 in 2009
  • ES6 still being defined

Support

  • ES3 Baseline, support to IE6
  • ES5 IE9+, FF4+, Chrome5+, Safari 5.1+
  • We'll start with only ES3

JavaScript Ubiquity

  • Browsers
  • Phones, native apps (Firefox OS)
  • Game Console browsers
  • Server (node.js)
  • JS powered Arduino bots
  • JS apps in TVs

REPL

Syllabus

  • JavaScript Fundamentals
  • Variables and Operators
  • Arrays
  • Statements
  • Primitives, Objects and Types
  • Functions and Scoping
  • Prototypes
  • The DOM
  • Events

Variables

5
x
var x = 5;
					

Variables

20
x
var x = 5;
x = 5 * 4;
					

Variables

5
x
8
y
var x = 5;
var y = 8;
					

Variables

?
x
?
y
var x = 5;
var y = 8;
x = x + 3 + y;
y = x * 2;
					

Variables

16
x
32
y
var x = 5;
var y = 8;
x = x + 3 + y;
y = x * 2;
					

Variables

'Tom'
name
var name = 'Tom';
					

Variables

true
isOn
var isOn = true;
					

Variables

Use var when defining!

Will explain scoping later

Arithmetic Operators

  • Addition: +
  • Subtraction: -
  • Division: /
  • Multiply: *
  • Modulo: %

Arithmetic Operators

var x = 5 * 6 + 1 / 4 - 5
x // 25.25
					

Arithmetic Operators

var x = 14 % 12
x // 2
					

Arithmetic Operators

var x = 5;
x++; // 5
x // 6
					

Arithmetic Operators

var x = 5;
++x; // 6
x // 6
					

Bitwise Operators

  • Binary AND: &
  • Binary OR: |
  • Binary XOR: ^
  • Binary NOT: ~
  • Left Shift: <<
  • Right Shift: >>
  • Zero Fill Right Shift: >>>

Bitwise Operators

7 & 9; // 1
//   0111
// & 1001
//   ----
//   0001
					

Assignment Operators

  • =
  • *=
  • +=
  • ...

Assignment Operators

var x = 5;
x *= 2; // x = x * 2;
x; // 10
					

Arrays

  • List of ordered elements
  • Mixed types
var a = ['abc', 4, false];
					

Accessing Elements

var x = ['a', 'b', 'c'];
x[0]; // 'a'
x[2]; // 'c'
					

Mutable Elements

var x = ['a', 'b', 'c'];
x[0]; // 'a'
x[0] = 'changed!';
x[0]; // 'changed!'
					

Mutable Length

var x = ['a', 'b', 'c'];
x.length; // 3
x[10] = 'j';
x.length // 11
					

Array Methods

Mutator Methods

  • array.push()
  • array.pop()
  • array.shift()
  • array.unshift()
  • array.splice()

Array Methods

Accessor Methods

  • array.indexOf()
  • array.concat()
  • array.join()
  • array.slice()

Pattern

function (val) {
  val = [].concat(val);
  // iterate over all
  // elements of `val`
}
					

Equality Operators

  • ==
  • !=
  • ===
  • !==

Conditional Statements

var user = 'Beth';
if (user === 'Beth')
  console.log("Yup, it's Beth");
					

Conditional Statements

var user = 'Beth';
if (user === 'Beth')
  console.log("Yup, it's Beth");
else
  console.log("Nope, not Beth");
					

Conditional Statements

var user = 'Beth';
if (user === 'Beth')
  console.log("Yup, it's Beth");
else if (user === 'Joe')
  console.log("Not Joe either");
else
  console.log("Who is this?");
					

Conditional Statements

var user = 'Beth';
if (user === 'Beth') {
  console.log("Yup, it's Beth");
  loginUser(user);
}
else
  console.log("Nope, not Beth");
					

Ternary Operators

var msg = loggedIn() ? 'profile' : 'sign in';
					

Pro Boolean Operators

var w = true && true;
var x = true && false;
var y = false && false;
var z = false && true;
					

Pro Boolean Operators

var w = true || true;
var x = true || false;
var y = false || false;
var z = false || true;
					

Pro Boolean Operators

var name = userName || 'Unknown';
					

Control Statements

var n = 0;
while (n < 10) {
  console.log(n + ' sheep');
  n++;
}
					

Control Statements

var u = ['joe', 'sue', 'tom'];
for (var i = 0; i < u.length; i++) {
  console.log('Here is ' + u[i]);
}
// "Here is joe"
// "Here is sue"
// "Here is tom"
					

Adding JS to a page

<html>
  <head></head>
  <body>
    <script src="script.js"></script>
  </body>
</html>
					

Syntax Time

  • ./problems/syntax/index.html
  • ./problems/syntax/euler1.js

Types

  • number
  • string
  • boolean
  • Object
  • Array
  • undefined
  • null

typeof

typeof 5; // 'number'
typeof 'hello'; // 'string'
typeof false; // 'boolean'
typeof []; // 'object'
					

Primitives

var n = 5;
var s = 'hello';
var b = true;
var a = [];
var o = {}; 
					

Primitives

typeof 5; // 'number'
typeof (new Number(5)); // 'object'
typeof 'hi'; // 'string'
typeof (new String('hi')); // 'object'
					

Primitives

5 === 5;
// true
new Number(5) === new Number(5);
// false
					

Types

typeof null; // 'object'
typeof undefined; // 'undefined'
null == undefined; // true
null === undefined; // false
					

Truthiness

var x = 'hello';
if (x) console.log('truthy!');
					

Truthy

  • non-0 numbers
  • non-0 length strings
  • All arrays
  • All objects (except null)
  • `true`

Falsy

  • 0
  • empty string ''
  • undefined
  • null
  • `false`

Truthiness

var a = [];
if (0)
  a.push('hello');

if (a)
  console.log('the array is truthy!');
					

Truthiness

var a = [];
if (a.length)
  console.log('hello!');
					

Type Coersion

// What happens?
5 === '5'
5 == '5'
null == undefined
null === undefined
					

Type Coersion

// What happens?
5 === '5'; // false
5 == '5'; // true
null == undefined; // true
null === undefined; // false
					

Uniqueness

var array1 = ['hi'];
var array2 = ['hi'];
var array3 = array1;

array1 !== array2;
array1 === array3;
					

Objects

Non primitives are objects

Hash, map, dictionary, key-value

Object Primitive

var o = {};
o.name = 'Jordan';
o.lang = 'JavaScript';

o.name; // 'Jordan'
o.hairColor; // undefined
					

Object Primitive

var o = {
  name: 'Jordan',
  lang: 'JavaScript'
};

o.name; // 'Jordan'
o.hairColor; // undefined
					

Object Primitive

var o = {};
o['name'] = 'Jordan';
o['lang'] = 'JavaScript';

o.name; // 'Jordan'
o.hairColor; // undefined
					

Object Primitive

var o = {};
o['π'] = Math.PI;
o['½'] = 0.5;
o[''] = null;
					

Object.keys()

var o = {
  name: 'Jordan',
  lang: 'JavaScript'
};

Object.keys(o);
// ['name', 'lang']
					

Dynamically accessing

var o = {
  name: 'Jordan',
  lang: 'JavaScript'
};
var keys = Object.keys(o);
for (var i = 0; i < keys.length; i++)
  console.log(keys+': '+o[keys[i]];
// 'name: Jordan'
// 'lang: JavaScript'
					

Object Example

An array of objects, each object representing a person with 'name', and 'age' properties.

Print out all properties of all objects one at a time, if the age is greater than some age.

Object Example

  • ./problems/objects/index.html
  • ./problems/objects/objects.js

Functions

Procedure that takes arguments and has a context

Functions

square(5); // 25
square(3); // 9

function square (x) {
  return x * x;
}
					

Function Declaration

square(5); // 25
square(3); // 9

function square (x) {
  return x * x;
}
					

Function Expression

square(5); // 25
square(3); // 9

var square = function (x) {
  return x * x;
}
					

Function Expression

square(5); // 25
square(3); // 9

// `square` IS NOT DEFINED!

var square = function (x) {
  return x * x;
}
					

Function Expression

var square = function (x) {
  return x * x;
}

square(5); // 25
square(3); // 9
					

Hoisting

console.log(y); // undefined

var y = 5;

console.log(y); // 5
					

Scope

var x = 5;

console.log(x); // 5
console.log(y); // throws

function fn () {
  var y = 1;
  console.log(x); // 5
  console.log(y); // 1
}
					

Closures

var incrementer = createIncrement(5);
incrementer(); // 6
incrementer(); // 7
incrementer(); // 8

function createIncrement (x) {
  var inc = x;
  return function () {
    return ++inc;
  }
}
					

First Class Objects

var doSomething = function () {}
[1,2,3].forEach(doSomething);
					

forEach

[1,2,3].forEach(function (x) {
  console.log(x);
});

forEach([1,2,3], function (x) {
  console.log(x);
});
					

map

[1,2,3].map(function (x) {
  return x * x;
});
// [1,4,9];

map([1,2,3], function (x) {
  return x * x;
});
// [1,4,9];
					

reduce

[1,2,3].reduce(function (sum, x) {
  return sum + x;
}, 0);
// 6
					

Functions

  • ./problems/functions/index.html
  • ./problems/functions/functions.js
  • Defining functions
  • Pass functions as variables
  • Using anonymous functions
  • Using closures

Callbacks

var id = 12345;
getUserInfo(id, function (user) {
  console.log(user);
});
					

Asynchronous (AJAX)

console.log(1);
getUserInfo(id, function (user) {
  console.log(2);
});
console.log(3);
// 1
// 3
// 2
					

XHR

API

Async

function fakeAjax (id, callback) {
  setTimeout(function () {
    callback({});
  }, 2000);
}
					

Async

  • ./problems/async/index.html
  • ./problems/async/async.js

Prototypes

var person = new Person();
					

Prototypes

var person = new Person();

function Person (options) {
  options = options || {};
  this.name = options.name;
  this.lang = options.lang;
}
					

Prototypes

var person = new Person({
  name: 'Brendan Eich'
});
person.name; // 'Brendan Eich'

function Person (options) {
  options = options || {};
  this.name = options.name;
  this.lang = options.lang;
}
					

Prototypes

function Person (options) {
  options = options || {};
  this.name = options.name;
}

Person.prototype.walk = function () {
  console.log(this.name + ' walks!');
  this.walking = true;
}

					

instanceof

var per = new Person();
var dev = new Developer();
per instanceof Person; // true
dev instanceof Person; // true
per instanceof Developer; // false
dev instanceof Developer; // true
per instanceof Object; // true
					

Prototypes

  • ./problems/prototypes/index.html
  • ./problems/prototypes/prototypes.js

ES5 Object Creation

var Person = {
  age: 0,
  walk: function () {}
};
var person = Object.create(Person, {
  name: 'Carrie Mathison',
  age: 34
});
					

Mixins

function extend (source, obj) {
  for (var prop in obj)
    source[prop] = obj[prop];
  return source;
}
					

Mixins

var JugglerMixin = {
  juggle: function () {}
};

extend(Person.prototype, JugglerMixin);
extend(Animal.prototype, JugglerMixin);
					

ES5 Getters/Setters

Object.defineProperty(p, 'full', {
  get: function () {
    return this.first + ' ' + this.last;
  },
  set: function (name) {
    this.first = name.split(' ')[0];
    this.last = name.split(' ')[1];
  }
});
					

Property Descriptors

docs

  • configurable
  • enumerable
  • value
  • writable
  • get/set

bind

function handleLogin (event) {
  loginUser(this);
}

function Person () {
  this.onLogin = handleLogin.bind(this);
}
					

call

function add (x, y) {
  return x + y;
}
function delay (fn) {
  return function () {
    var args = arguments;
    setTimeout(function () {
      fn.call(null, args[0], args[1]);
    }, 1000);
  }
}
					

call

var delayedAdd = delay(add);
delayedAdd(1, 3);
// 4
				

apply

function delay (fn) {
  return function () {
    var args = arguments;
    setTimeout(function () {
      fn.apply(null, args);
    }, 1000);
  }
}
					

apply

var delayedAdd = delay(add);
delayedAdd(1,2,3,4);
// 10
					

DOM

DOM

  • ./problems/dom/index.html
  • ./problems/dom/dom.js

Thanks!