JavaScript – An Introduction – ECMAScript



JavaScript – An Introduction – ECMAScript

2 0


introduction-to-javascript

A gentle introduction to JavaScript

On Github mshalaby / introduction-to-javascript

JavaScript

An Introduction

by Mohammed Shalaby

What is JavaScript?

A dynamic object-oriented general-purpose programming language

History

  • Developed in 10 days in May 1995 by Brendan Eich at Netscape
  • Names: Mocha, LiveScript then JavaScript

ECMAScript

Standard of the core language of JavaScript

Also used in non-browser environments e.g. node.js

Provides:

  • Syntax
  • Types
  • Inheritance
  • Built-in Objects
  • Error handling
  • Global object (Non-browser APIs)

Versions of ECMA-262:

  • ES3 (Dec 1999)
  • ES5 (Dec 2009)
  • ES5.1 (Jun 2011)
  • ES6 / ES 2015 (Jun 2015)

Syntax

C-like (similar to Java)

Comments

// one line comment

/*
  Multi-line
  comment
*/

Variables

Declared using var

var x = 2;   // x is declared and initialized

var y;       // y is only declared (value is undefined)

function test() {
  var z = 3;
  k = 5;    // missing var
}

// x, y & k are global variables
// z is a local variable

Block statement

Declared using var

var x = 1;
{
  var x = 2;
}
console.log(x); // outputs 2

Conditional statement

if (x == 'yes') {
  doSomething();
} else {
  doSomethingElse();
}

if (x == 'yes') {
  doSomething();
} else if (x == 'no') {
  doSomethingElse();
}

Loops

for (var x = 0; x < 10; x++) {
  doSomething(x);
}

while (x < 10) {
  doSomething(x);
  x++;
}

Types (Values)

Simple types

  • Numbers
  • Strings
  • Booleans
  • null
  • undefined

Objects

Numbers

Only one number type

100, 100.0, 1e2 are equivalent

64-bit floating point (same as Java's double)

0.1 + 0.2      // 0.30000000000000004

NaN (Not a Number)

Special Number

typeof NaN       // "number"

Result of erroneous operations

2 * 'a'          // NaN

Toxic

5 + NaN          // NaN

Not equal to any value (including itself)

NaN == NaN       // false

isNaN(NaN)       // true

Infinity

Special Number

 1 / 0           // Infinity

 1 / Infinity    // 0

-1 / 0           // -Infinity

Represents numbers > 1.79769313486231580e+308

1.8e308          // Infinity

isFinite function

You can use it to check for Infinity, -Infinity & NaN

isFinite(NaN)          // false

isFinite(Infinity)     // false

isFinite(-Infinity)    // false

isFinite(1.7e+308)     // true

Number function

Converts a value into a number

Number('')          // 0

Number('0032')      // 32

Number('123abc')    // NaN

Number('abc')       // NaN

So does the '+' prefix operator

+''                // 0

+'0032'            // 32

+'123abc'          // NaN

+'abc'             // NaN

parseInt function

Also converts a value into a number

parseInt('123', 10)     // 123

Stops at first non-digit character

parseInt('123abc', 10)     // 123

If no radix is passed it defaults to 10

parseInt('32')         // 32   (as decimal)

Always specify the radix

parseInt('0032', 10)   // 32

parseInt('0032', 8)    // 26

parseInt('11', 2)      //  3

Math

An object containing methods that act on numbers

abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan
Math.floor(12.53)          // 12

Also contains some useful constants

E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2
Math.PI                   // 3.141592653589793

Strings

0 or more 16-bit characters

A character is just a String of length 1

Immutable

length

number of 16-bit characters

'abc'.length      // 3

String literal

'abc' == "abc"    // true

Concatenation

'Java' + 'Script'     // 'JavaScript'

String function

Converts a value into a string

String(123)           // '123'

Another way

'' + 123           // '123'

String methods

some examples

'cat'.toUpperCase()               // 'CAT'
'bat'.charAt(1)                   // 'a'
'hello'.replace(/llo/, 'y')       // 'hey'
'Alexandria'.indexOf('x')         // 3
'banana'.lastIndexOf('n')         // 4
'world wide web'.match(/(w\w*)/g) // ["world", "wide", "web"]

Boolean

true - false

Boolean function

Converts a value into a boolean

Boolean(value)       // true or false

!! prefex operator

!! value       // true or false

Falsy values

6 possible falsy values

!! false         // false

!! null          // false

!! undefined     // false

!! ''            // false

!! 0             // false

!! NaN           // false

All other values are truthy

!! '0'          // true

null & undefined

null

A deliberate non-value

var a = null;

typeof a;     // 'object'

undefined

An uninitialized value

var a;

typeof a;     // 'undefined'

Objects

An object is a container of properties

Object constructor

A built in function for creating objects

var object = new Object();

Object literal

Very convenient for creating new objects

var object = {};
var person = { 'first-name': 'John' };
var city = {
  name: 'Alexandria',
  location: { latitude: 31.2, longitude: 29.9 }
};

Reference

Passed around by reference

var a = b = c = {};              // the same empty object
var a = {}, b = {}, c = {};      // different empty objects

Property access

person['first-name']            // 'John'

person['last-name'] = 'Smith';

person.age = 28;

Missing properties

person.nickname        // undefined

delete

removes properties

var person = { name: 'John', age: 20 };

delete person.age;

person.age                       // undefined

Prototype

Every object is linked to a prototype object

Provides inheritance

Protypes hold common functionality & data

Specifying a prototype

var p = {foo: 'bar'};

var a = Object.create(p);
var b = Object.create(p);

a.foo          // 'bar'
b.foo          // 'bar'

Another way

function A (){
}

A.prototype = {foo: 'bar'};

var a = new A();
var b = new A();

a.foo          // 'bar'
b.foo          // 'bar'

Masking a prototype property

a.foo = 'blah';  // Added foo property to a
a.foo            // 'blah'
b.foo            // 'bar'

Functions

The best thing in JavaScript

Functions are objects

A function has a prototype property

Code reuse, Information hiding

Function Literal

4 parts:

function add (a, b) {
  return a + b;
};

add(1, 2)            // 3

Functions as Methods

When stored as a property of an object

var counter = {
  value: 0,
  increment: function (inc) {
    this.value += inc;
  }
};

counter.increment(2);
counter.increment(1);

counter.value;                      // 3

Functions as Constructors

Invoked with new prefix

New object linked to function's prototype property

function Car (speed) {
  this.speed = speed;
};

Car.prototype.move = function() {
  return 'moving at ' + this.speed;
};

var my_car = new Car('40 k/h');
var racing_car = new Car('200 k/h');

my_car.move();                 // moving at 40 k/h
racing_car.move();             // moving at 200 k/h

Apply

apply is a method of functions

2 parameters: value for this & array of arguments

var counter = { value: 1 };

function increment (inc) {
  this.value += inc;
}

increment.apply(counter, [3]);

counter.value             // 4

Arguments

array-like object holding passed parameters

function sum () {
  var i, s = 0;

  for (i = 0; i < arguments.length; i += 1) {
      s += arguments[i];
  }

  return s;
};

sum(4, 8, 15, 16, 23, 42)         // 108

Scope

No block scope

Only function scope

function foo () {
  var x = 1;

  var bar = function () {
    var x = 2
    console.log(x); // 2
  };

  bar();

  console.log(x) // 1
};

Closure

Inner functions have access to outer function's parameters and variables.

function incrementMaker(val) {
  var step = 2;

  return function (){
    val += step;

    return val;
  };
}

var increment = incrementMaker(3);

increment();              // 5
increment();              // 7

Arrays

Array-like objects

No linear allocated memory or computed offest access

Array Literal

var a = [];
var misc = [
  'string',
  98.6,
  true,
  null,
  undefined,
  ['nested', 'array'],
  {x: 1}
];

length

length property is not upper bound

var a = [];
a.length          // 0
a[10] = 1;
a.length          // 11
a[4]              // undefined

Array methods

var a = [0, 4, 9];
a.toString()
a.toLocaleString()
a.concat(item [,itemN]) // Returns a new array with added items
a.join(sep)             // Joins array elements into a string
a.pop()	                // Removes and returns the last item
a.push(item [,itemN])   // Adds one or more items to the end
a.reverse()             // [9, 4, 0]
a.shift()               // Removes and returns the first item
a.slice(start, end)     // Returns a sub-array
a.sort([cmpfn])         // Takes an optional comparison function
a.splice(start, delcount[, itemN]) // modify by replacing a section
a.unshift([item])       // Add one item to the start

Manipulating Webpage Elements

HTML

Provides structure & semantic content

<p>This is a paragraph</p>
<ul>
  <li>item</li>
  <li>another item</li>
</ul>

CSS

Provides style

<style>
  li.selected { background: yellow; }
</style>
            ...
<p>This is a paragraph</p>
<ul>
  <li class="selected">item</li>
  <li>another item</li>
</ul>

JavaScript

Provides interactivity

<style>
  li.selected { background: yellow; }
</style>

<script>
  function clickHandler(event) {
    event.target.classList.add('selected');
  }
</script>
            ...
<p>This is a paragraph</p>
<ul onclick="clickHandler(event)">
  <li>item</li>
  <li>another item</li>
</ul>

How to run JavaScript in a Webpage?

Directly within HTML script element

Script element with code inside

<script>
  alert('Hello');
</script>

Using a separate file

Store source code in a separate file e.g. 'scripts.js'

alert('Hello');

Script element with src attribute

Browser issues a request for it

<script src="script.js"></script>

Using a separate file from external sites

Set the src attribute to the URL for the external file

Browser issues a request for it

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

Address Bar!

preceded by "javascript:"

javascript:alert('hello')

href of an anchor

code also preceded by "javascript:"

<a href="javascript:alert('hello');">click me</a>

Event handler attributes of elements

<input type="button" onclick="alert('hello');" value="Click Me" />

Accessing the HTML elements

The document object

Provided by the browser to represent the tree of HTML nodes

By id

html

<p id="my-element">Text here</p>

script

var p = document.getElementById('my-element');
p.innerHTML // "Text here"

By tag name

html

<div>
  <p>One</p>
  <p>Two</p>
</div>
<p>Three</p>

script

var paragraphs = document.getElementsByTagName('p');  // returns an array
paragraphs[1].innerHTML      // Two

Creating HTML elements

Appending to an existing element

html

<div id="container" >
</div>

script

var container = document.getElementById('container');

var p = document.createElement('p');
p.innerHTML = "Some text"

container.appendChild(p);

html

<div id="container" >
  <p>Some text</p>
</div>

Setting innerHTML

Allows creating multiple / nested elements

html

<div id="container" >
</div>

script

var container = document.getElementById('container');

container.innerHTML = '<p>One</p><p>Two<span>!</span></p>';

html

<div id="container" >
  <p>One</p>
  <p>Two<span>!</span></p>
</div>

Handling Events on Elements

Document loadded?

script

window.onload = function () {
  alert('ready');
};

Click Events

html

<div id="container" >
  <p>One</p>
</div>

script

var container = document.getElementById('container');

container.onclick = function (event) {
  alert(event.target.tagName);
};

alerts 'p' on clicking the p element

Keyboard Events

html

<div>
  <input id="my-input" type="text" />
</div>

script

var inputElement = document.getElementById('my-input');

container.onkeyup = function (event) {
  alert(event.keyCode);
};

alerts 13 on pressing the Enter key

For Modern Browsers

use addEventListener

html

<div id="container" >
  <p>One</p>
</div>

script

var container = document.getElementById('container');

container.addEventListener('click', function (event) {
  alert(event.target.tagName);
}, true);

alerts 'p' on clicking the p element

Removing Elements

removeChild

html

<div id="container" >
  <p>One</p>
</div>

script

var container = document.getElementById('container');
var p = container.firstChild;

container.removeChild(p);

html

<div id="container" >
</div>

Speaking to the Server!!

XMLHttpRequest ?? WHAT??!!

Never mind this function... for now :)

function request(url, callback) {
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      if (callback) { callback(this.responseText) }
    }
  }

  xmlhttp.open("GET",url ,true);
  xmlhttp.send();
}

It wraps the complexity of talking to the server for you.

And allows you to just use this simple call

request('items.json', function(responseText){
  // Do somthing with the response text
  console.log(JSON.parse(responseText));
});

Demo

Links

Demo page

Demo source files

Assignment

Links

Assignment page

Assignment source files

Resources

Mozilla Developer Network

Document Object Model (DOM) | MDN

Learn JavaScript | MDN

A re-introduction to JavaScript (JS Tutorial) - JavaScript | MDN

Douglas Crockford

Douglas Crockford's Javascript

JavaScript: The Good Parts

Q & A!

Thank You!