JavaScript*

* for Those Wanting to Get Started with

Marek Matczak

Tomasz Szewców

Inspired by

Picture taken from: http://frightanic.com/category/software-development/javascript/

JavaScript...

...has nothing common with Java * except for some key words

...is more like “Lisp in C's clothing” *Douglas Crockford

...has objects, but is class-free

...is of single-threaded nature

...has asynchronous programming model

...is object oriented and functional at the same time

Declaring variables

Always use var to declare variables

If you don't, they become global variables

Variable declarations get hoisted to the top of a function...

...which may be confusing:


var myVar = 'global';
var myFunction = function () {
    console.log(myVar); // undefined
    var myVar = 'local';
    console.log(myVar); // 'local'
};
myFunction();
					

The above code behaves as if it looked like this:


var myVar = 'global';
var myFunction = function () {
    var myVar;
    console.log(myVar); // undefined
    myVar = 'local';
    console.log(myVar); // 'local'
};
myFunction();
					

Single var pattern

Eliminates logical errors caused by hoisting


var a = 1,
    b = 2,
    sum = a + b,
    myVar,
    hello = function () {
        return 'Hello!';
    };
					

Objects

can be created in a very convenient way with object literals:


var emptyObject = {},
    person = {
      firstName : 'John',
      lastName : 'Example',
      age : 30
    };
					

Objects

Values' retrieval


var emptyObject = {},
    person = {
        firstName: 'John',
        lastName: 'Example',
        age: 30
    };

// retrieval
person.firstName // 'John'
person['lastName'] // 'Example'
person.salutation // undefined
salutation = person.salutation || ''; // the default operator
person.address.street // throws TypeError
street = person.address && person.address.street // undefined
					

Objects

Values' update and properties' removal


var person = {
        firstName: 'John',
        lastName: 'Example',
        age: 30
    },
    salutation, street;

// update
person['firstName'] = 'Joe';
person.age = 33;

// delete
delete person.age;
					

Functions

are objects

can be created with function literals:


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

add(1, 2); // 3
					

Functions

stored as properties of objects...


var person = {
    firstName: 'John',
    lastName: 'Example',
    age: 30,
    letMeIntroduceMyself: function () {
        return 'My name is ' + this.firstName + ' ' + this.lastName;
    }
};

person.letMeIntroduceMyself(); // My name is John Example
person.firstName // 'John' - no privacy
					

...are called methods

Scope

is defined by functions, and no {} blocks


var myFun = function (someInput) {
    var a = 1,
        b = 2,
        yourFun = function () {
            var b = 22,
                c = 3;
            // at this point a = 1, b = 22, c = 3
            a = 11;
        };
    // at this point a = 1, b = 2, c is not defined
    yourFun();
    // at this point a = 11, b = 2, c is not defined
};
myFun();
					

Closure

enables a function to keep its creation context


var myObjectFactory = function (param) {
        var value = 'Value';

        return {
            theseAreMySecrets: function () {
                return 'value = ' + value + ', param = ' + param;
            }
        };
    },
    myObject = myObjectFactory('Param');
myObject.theseAreMySecrets(); // value = Value, param = Param
myObject.value; // undefined
					

...even if its lifetime is shorter than the function's one

Module Pattern

makes use of function scope and closure


var person = (function () {
    var details = {
        firstName: 'John',
        lastName: 'Example',
        age: 30
    };

    return {
        letMeIntroduceMyself: function () {
            return 'My name is ' +
                details.firstName + ' ' + details.lastName;
        }
    };
})();

person.letMeIntroduceMyself(); // My name is John Example
person.details; // undefined
					

is widely used for programming services in

Exercise

  1. Create a module todos using the module pattern.
  2. The todos module keeps its list of ToDos private.
  3. Each ToDo is made up of a title and a flag done .
  4. The todos module exposes the numberOfDoneToDos method.

Constructor function

is intended to be invoked with the new prefix (forgetting it makes this bound to the global object!)

creates a new object with a hidden link to its prototype

is kept in a variable with a capitalized name by convention


var Person = function () {
      this.firstName = 'John';
      this.lastName = 'Example';
      this.age = 30;
    }, johnExample;

Person.prototype.letMeIntroduceMyself = function () {
  return 'My name is ' + this.firstName + ' ' + this.lastName;
};

johnExample = new Person();
johnExample.letMeIntroduceMyself();  // My name is John Example
johnExample.firstName; // 'John' - no privacy
					

is used for defining controllers in

Exercise

  1. Define a constructor function ToDoCtrl passing it the todos module.
  2. ToDoCtrl has a userName property and exposes the summary method.
  3. The summary method calls the todos module and prints a summary on the number of ToDos done by the user till now.

Prototypal inheritance


var create = function (from) {  // added to ECMAScript 5 as Object.create
      var F = function () {};
      F.prototype = from;
      return new F();
    },
    parent = {
      firstName : 'John',
      lastName : 'Example',
      letMeIntroduceMyself : function () {
        return 'My name is ' + this.firstName + ' ' + this.lastName;
      }
    }, child;
child = create(parent);
child.firstName = 'Joe';
parent.letMeIntroduceMyself();  // My name is John Example
child.letMeIntroduceMyself();  // My name is Joe Example
					

In scopes prototypically inherit from each other

Unit testing - tools

  • Karma - tool used to spawn a web server which loads your application's source code and executes your tests.
  • Jasmine - BDD framework for JavaScript, provides functions to help with structuring tests and making assertions.

https://docs.angularjs.org/guide/unit-testing

Structuring tests


describe('A suite', function() {
      it('contains spec with an expectation', function() {
        expect(true).toBe(true);
      });
});
      

Karma configuration


// install Karma
npm install karma
		  

// install plugins and tools
npm install karma-jasmine
npm install karma-phantomjs-launcher
npm install karma-chrome-launcher
npm install jasmine-core
npm install phantomjs-prebuilt
		  

// run Karma
./node_modules/karma/bin/karma start / init / run
// alternative
npm install -g karma-cli
karma start / init / run
		  

http://karma-runner.github.io/0.13/intro/installation.html

Summary

http://www.flickr.com/photos/natekoechley/2853942919/