Category Archives: AngularJs

New number and Math features in ES6

By Axel Rauschmayer

This blog post describes the new number and Math features of ECMAScript 6.

Overview

You can now specify integers in binary and octal notation:

    > 0xFF // ES5: hexadecimal
    255
    > 0b11 // ES6: binary
    3
    > 0o10 // ES6: octal
    8

The global object Number gained a few new properties. Among others:

  • Number.EPSILON for comparing
  • Methods and constants for determining whether an integer is within the signed 53 bit range that can be safely represented by JavaScript.

New integer literals

ECMAScript 5 already has literals for hexadecimal integers:

    > 0x9
    9
    > 0xA
    10
    > 0x10
    16
    > 0xFF
    255

ECMAScript 6 brings two new kinds of integer literals:

  • Binary literals have the prefix 0b or 0B:

        > 0b11
        3
        > 0b100
        4
    
  • Octal literals have the prefix 0o or 0O (yes, that’s a zero followed by the capital letter O; you’ll be fine if you use the first variant):

        > 0o7
        7
        > 0o10
        8
    

Remember that the method Number.prototype.toString(radix) can be used to convert numbers back:

    > (255).toString(16)
    'ff'
    > (4).toString(2)
    '100'
    > (8).toString(8)
    '10'

Use case for octal literals: Unix-style file permissions

In the Node.js file system module, several functions have the parameter mode. Its value is used to specify file permissions, via an encoding that is a holdover from Unix:

  • Permissions are specified for three categories of users:
    • User: the owner of the file
    • Group: the members of the group associated with the file
    • All: everyone
  • Per category, the following permissions can be granted:
    • r (read): the users in the category are allowed to read the file
    • w (write): the users in the category are allowed to change the file
    • x (execute): the users in the category are allowed to run the file

That means that permissions can be represented by 9 bits (3 categories with 3 permissions each):

User Group All
Permissions r, w, x r, w, x r, w, x
Bit 8, 7, 6 5, 4, 3 2, 1, 0

The permissions of a single category of users are stored in 3 bits:

Bits Permissions Octal digit
000 ––– 0
001 ––x 1
010 –w– 2
011 –wx 3
100 r–– 4
101 r–x 5
110 rw– 6
111 rwx 7

That means that octal numbers are a compact representation of all permissions, you only need 3 digits, one digit per category of users. Two examples:

  • 755 = 111,101,101: I can change, read and execute; everyone else can only read and execute.
  • 640 = 110,100,000: I can read and write; group members can read; everyone can’t access at all.

parseInt() and the new integer literals

parseInt() has the following signature:

    parseInt(string, radix?)

It provides special support for the hexadecimal literal notation – the prefix 0x (or 0X) of string is removed if:

  • radix is missing or 0. Then radix is set to 16.
  • radix is already 16.

For example:

    > parseInt('0xFF')
    255
    > parseInt('0xFF', 0)
    255
    > parseInt('0xFF', 16)
    255

In all other cases, digits are only parsed until the first non-digit:

    > parseInt('0xFF', 10)
    0
    > parseInt('0xFF', 17)
    0

parseInt() does not have special support for binary or octal literals!

    > parseInt('0b111')
    0
    > parseInt('0b111', 2)
    0
    > parseInt('111', 2)
    7
    
    > parseInt('0o10')
    0
    > parseInt('0o10', 8)
    0
    > parseInt('10', 8)
    8

If you want to parse these kinds of literals, you need to use Number():

    > Number('0b111')
    7
    > Number('0o10')
    8

New Number constructor properties

This section describes new properties that the constructor Number has picked up in ECMAScript 6.

Previously global functions

Four number-related functions are already available as global functions and have been added (with no or little modifications) to Number, as methods: isFinite, isNaN, parseFloat and parseInt.

Number.isFinite(number)

Is number an actual number (neither Infinity nor -Infinity nor NaN)?

    > Number.isFinite(Infinity)
    false
    > Number.isFinite(-Infinity)
    false
    > Number.isFinite(NaN)
    false
    > Number.isFinite(123)
    true

The advantage of this method is that it does not coerce its parameter to number (whereas the global function does):

    > Number.isFinite('123')
    false
    > isFinite('123')
    true
Number.isNaN(number)

Is number the value NaN? Making this check via === is hacky. NaN is the only value that is not equal to itself:

    > let x = NaN;
    > x === NaN
    false

Therefore, this expression is used to check for it

    > x !== x
    true

Using Number.isNaN() is more self-descriptive:

    > Number.isNaN(x)
    true

Number.isNan() also has the advantage of not coercing its parameter to number (whereas the global function does):

    > Number.isNaN('???')
    false
    > isNaN('???')
    true
Number.parseFloat and Number.parseInt

The following two methods work exactly like the global functions with the same names. They were added to Number for completeness sake; now all number-related functions are available there.

  • Number.parseFloat(string)
  • Number.parseInt(string, radix)

Number.EPSILON

Especially with decimal fractions, rounding errors can become a problem in JavaScript. For example, the

    > 0.1 + 0.2 === 0.3
    false

Number.EPSILON specifies a reasonable margin of error when comparing floating point numbers. It provides a better way to compare floating point values, as demonstrated by the following function.

    function epsEqu(x, y) {
        return Math.abs(x - y) < Number.EPSILON;
    }
    console.log(epsEqu(0.1+0.2, 0.3)); // true

Number.isInteger(number)

JavaScript has only floating point numbers (doubles). Accordingly, integers are simply floating point numbers without a decimal fraction.

Number.isInteger(number) returns true if number is a number and does not have a decimal fraction.

    > Number.isInteger(-17)
    true
    > Number.isInteger(33)
    true
    > Number.isInteger(33.1)
    false
    > Number.isInteger('33')
    false
    > Number.isInteger(NaN)
    false
    > Number.isInteger(Infinity)
    false

Safe Integers

JavaScript numbers have only enough storage space to represent 53 bit signed integers. That is, integers i in the range −2^53^ < i < 2^53^ are safe. What exactly that means is explained momentarily. The following properties help determine whether a JavaScript integer is safe:

  • Number.isSafeInteger(number)
  • Number.MIN_SAFE_INTEGER
  • Number.MAX_SAFE_INTEGER

The notion of safe integers centers on how mathematical integers are represented in JavaScript. In the range (−2^53^, 2^53^) (excluding the lower and upper bounds), JavaScript integers are safe: there is a one-to-one mapping between them and the mathematical integers they represent.

Beyond this range, JavaScript integers are unsafe: two or more mathematical integers are represented as the same JavaScript integer. For example, starting at 2^53^, JavaScript can represent only every second mathematical integer:

    > Math.pow(2, 53)
    9007199254740992
    
    > 9007199254740992
    9007199254740992
    > 9007199254740993
    9007199254740992
    > 9007199254740994
    9007199254740994
    > 9007199254740995
    9007199254740996
    > 9007199254740996
    9007199254740996
    > 9007199254740997
    9007199254740996

Therefore, a safe JavaScript integer is one that unambiguously represents a single mathematical integer.

The properties of Number

The two Number properties specifying the lower and upper bound of safe integers could be defined as follows:

    Number.MAX_SAFE_INTEGER = Math.pow(2, 53)-1;
    Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;

Number.isSafeInteger() determines whether a JavaScript number is a safe integer and could be defined as follows:

    Number.isSafeInteger = function (n) {
        return (typeof n === 'number' &&
            Math.round(n) === n &&
            Number.MIN_SAFE_INTEGER <= n &&
            n <= Number.MAX_SAFE_INTEGER);
    }

For a given value n, this function first checks whether n is a number and an integer. If both checks succeed, n is safe if it is greater than or equal to MIN_SAFE_INTEGER and less than or equal to MAX_SAFE_INTEGER.

Safe results of arithmetic computations

How can we make sure that results of arithmetic computations are correct? For example, the following result is clearly not correct:

    > 9007199254740990 + 3
    9007199254740992

We have two safe operands, but an unsafe result:

    > Number.isSafeInteger(9007199254740990)
    true
    > Number.isSafeInteger(3)
    true
    > Number.isSafeInteger(9007199254740992)
    false

The following result is also incorrect:

    > 9007199254740995 - 10
    9007199254740986

This time, the result is safe, but one of the operands isn’t:

    > Number.isSafeInteger(9007199254740995)
    false
    > Number.isSafeInteger(10)
    true
    > Number.isSafeInteger(9007199254740986)
    true

Therefore, the result of applying an integer operator op is guaranteed to be correct only if all operands and the result are safe. More formally:

    isSafeInteger(a) && isSafeInteger(b) && isSafeInteger(a op b)

implies that a op b is a correct result.

Source of this section

Math

The global object Math has several new methods in ECMAScript 6.

Various numerical functionality

Math.sign(x)

Returns the sign of x as -1 or +1. Unless x is either NaN or zero; then x is returned[1].

[1]: While that is something that you normally don’t see, that means that -0 produces the result -0 and +0 produces the result +0.

    > Math.sign(-8)
    -1
    > Math.sign(3)
    1
    
    > Math.sign(0)
    0
    > Math.sign(NaN)
    NaN
    
    > Math.sign(-Infinity)
    -1
    > Math.sign(Infinity)
    1
Math.trunc(x)

Removes the decimal fraction of x.

    > Math.trunc(3.1)
    3
    > Math.trunc(3.9)
    3
    > Math.trunc(-3.1)
    -3
    > Math.trunc(-3.9)
    -3
Math.cbrt(x)

Returns the cube root of x (∛x).

    > Math.cbrt(8)
    2

Using 0 instead of 1 with exponentiation and logarithm

JavaScript numbers (doubles) close to zero are stored with a higher precision.

1 × 10^−16^

    > 1e-16 === 0
    false
    > 1 + 1e-16 === 1
    true
Math.expm1(x)

Returns Math.exp(x)-1. The inverse of Math.log1p().

Therefore, this method provides higher precision whenever Math.exp() has results close to 1.

    > Math.expm1(1e-10)
    1.00000000005e-10
    > Math.exp(1e-10)-1
    1.000000082740371e-10
    > var Decimal = require('decimal.js').config({precision:50});
    > new Decimal(1e-10).exp().minus(1).toString()
    '1.000000000050000000001666666666708333333e-10'
Math.log1p(x)

Returns Math.log(1 + x). The inverse of Math.expm1().

Therefore, this method lets you specify parameters that are close to 1 with a higher precision.

We have already established that 1 + 1e-16 === 1. Therefore, it is no surprise that the following two calls of log() produce the same result:

    > Math.log(1 + 1e-16)
    0
    > Math.log(1 + 0)
    0

In contrast, log1p() produces different results:

    > Math.log1p(1e-16)
    1e-16
    > Math.log1p(0)
    0

Logarithms to base 2 and 10

Math.log2(x)

Computes the logarithm to base 2.

    > Math.log2(8)
    3
Math.log10(x)

Computes the logarithm to base 10.

    > Math.log10(100)
    2

Support for compiling to JavaScript

Emscripten pioneered a coding style that was later picked up by asm.js: The operations of a virtual machine (think bytecode) are expressed in static subset of JavaScript. That subset can be executed efficiently by JavaScript engines: If it is the result of a compilation from C++, it runs at about 70% of native speed.

Math.fround(x)

Rounds x to a 32 bit floating point value (float). Used by asm.js to tell an engine to internally use a float value.

Math.imul(x, y)

Multiplies the two 32 bit integers x and y and returns the lower 32 bits of the result. This is the only 32 bit basic math operation that can’t be simulated by using a JavaScript operator and coercing the result back to 32 bits. For example, idiv could be implemented as follows:

    function idiv(x, y) {
        return (x / y) | 0;
    }

In contrast, multiplying two large 32 bit integers may produce a double that is so large that lower bits are lost.

Bitwise operations

  • Math.clz32(x)
    Counts the leading zero bits in the 32 bit integer x.

        > Math.clz32(0b01000000000000000000000000000000)
        1
        > Math.clz32(0b00100000000000000000000000000000)
        2
        > Math.clz32(2)
        30
        > Math.clz32(1)
        31
    

Trigonometric methods

  • Math.sinh(x)
    Computes the hyperbolic sine of x.

  • Math.cosh(x)
    Computes the hyperbolic cosine of x.

  • Math.tanh(x)
    Computes the hyperbolic tangent of x.

  • Math.asinh(x)
    Computes the inverse hyperbolic sine of x.

  • Math.acosh(x)
    Computes the inverse hyperbolic cosine of x.

  • Math.atanh(x)
    Computes the inverse hyperbolic tangent of x.

  • Math.hypot(...values)
    Computes the square root of the sum of squares of its arguments.

Source:: 2ality

Using the ES6 transpiler Babel on Node.js

By Axel Rauschmayer

This blog post explains how to use the ES6 transpiler Babel with Node.js. You can download the code shown in this post on GitHub. For further information on ECMAScript 6, consult the ebook “Exploring ES6”.

Warning: The approach explained in this post is convenient for experiments and development. But it uses on-the-fly transpilation, which may be too slow for your production code. Then you can transpile as a build step (as explained in the Babel documentation).

Running normal Node.js code via Babel

The npm package babel brings Babel support to Node.js:

    $ npm install --global babel

This package contains the shell script babel-node, which is a Babel-ified version of node. It compiles everything from ES6 to ES5 that is run or required. For example, you can start a REPL via the following shell command:

    $ babel-node

In the REPL, you can use ES6:

    > [1,2,3].map(x => x * x)
    [ 1, 4, 9 ]

babel-node also lets you run Node.js scripts such as the following one.

    // point.js
    export class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    }
    if (require.main === module) {
        let pt = new Point(7,4);
        console.log(`My point: ${JSON.stringify(pt)}`);
    }

The following shell command runs point.js:

    $ babel-node point.js 
    My point: {"x":7,"y":4}

The package babel has many more features, which are all documented on the Babel website. For example, from within a normal Node module, you can install a “require hook”, which compiles all required modules via Babel (except, by default, modules in node_modules).

Running Jasmine unit tests via Babel

Another npm package, babel-jest, is a preprocessor for the Jasmine-based unit testing tool Jest.

One way to install babel-jest is by mentioning it in the devDependencies of your package.json:

    {
      "devDependencies": {
        "babel-jest": "*",
        "jest-cli": "*"
      },
      "scripts": {
        "test": "jest"
      },
      "jest": {
        "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
        "testFileExtensions": ["js"],
        "moduleFileExtensions": ["js", "json"],
        "testDirectoryName": "spec"
      }
    }

Afterwards, you only need to execute the following command inside the directory of package.json and both babel-jest and a command line interface (CLI) for Jest will be installed.

    npm install

The configuration options for Jest are documented on its website. I have used testDirectoryName to specify that the tests are inside the directory spec (the default is __tests__). Let’s add the following test file to that directory:

    // spec/point.spec.js
    jest.autoMockOff();
    import { Point } from '../point';
    
    describe('Point', function() {
        it('sets up instance properties correctly', function() {
            let p = new Point(1, 5);
            console.log(JSON.stringify(p));
            expect(p.x).toBe(1);
            expect(p.y).toBe(5);
        });
    });

Because we have specified scripts.test in package.json, we can run all tests inside spec/ via the following command:

    npm test

Source:: 2ality

Classes in ECMAScript 6 (final semantics)

By Axel Rauschmayer

Recently, TC39 decided on the final semantics of classes in ECMAScript 6 [2]. This blog post explains how their final incarnation works. The most significant recent changes were related to how subclassing is handled.

Overview

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString () {
            return '(' + this.x + ', ' + this.y + ')';
        }
    }
    
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y);
            this.color = color;
        }
        toString () {
            return super.toString() + ' in ' + this.color;
        }
    }
    
    let cp = new ColorPoint(25, 8, 'green');
    cp.toString(); // '(25, 8) in green'
    
    console.log(cp instanceof ColorPoint); // true
    console.log(cp instanceof Point); // true

The essentials

Base classes

A class is defined like this in ECMAScript 6 (ES6):

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString () {
            return '(' + this.x + ', ' + this.y + ')';
        }
    }

You use this class just like an ES5 constructor functions:

    > var p = new Point(25, 8);
    > p.toString()
    '(25, 8)'

In fact, classes internally produce constructors. That is, the ES6 class Point is roughly equivalent to the following ES5 code:

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype.toString = function () {
        return '(' + this.x + ', ' + this.y + ')';
    };

A class body can only contain methods, no data properties. Prototypes having data properties is generally considered an anti-pattern, so this just enforces a best practice.

Class declarations are not hoisted

Function declarations are hoisted: When entering a scope, the functions that are declared in it are immediately available – independently of where the declarations happen. That means that you can call a function that is declared later:

    foo(); // works, because `foo` is hoisted
    
    function foo() {}

In contrast, class declarations are not hoisted. Therefore, a class only exists after execution reached its definition and it was evaluated. Accessing it beforehand leads to a ReferenceError:

    new Foo(); // ReferenceError
    
    class Foo {}

The reason for this limitation is that classes can have an extends clause whose value is an arbitrary expression. That expression must be evaluated in the proper “location”, its evaluation can’t be hoisted.

Not having hoisting is less limiting than you may think. For example, a function that comes before a class declaration can still refer to that class, but you have to wait until the class declaration has been evaluated before you can call the function.

    function functionThatUsesBar() {
        new Bar();
    }
    
    functionThatUsesBar(); // ReferenceError
    class Bar {}
    functionThatUsesBar(); // OK

Getters and setters

The syntax for getters and setters is just like in ECMAScript 5 object literals:

    class MyClass {
        get prop() {
            return 'getter';
        }
        set prop(value) {
            console.log('setter: '+value);
        }
    }

You use MyClass as follows.

    > let inst = new MyClass();
    > inst.prop = 123;
    setter: 123
    > inst.prop
    'getter'

Generator methods

If you prefix a method definition with an asterisk (*), it becomes a generator method [3]. Among other things, a generator is useful for defining the method whose key is Symbol.iterator. That method makes objects iterable [3], which means that they can be iterated over via the for-of loop and other ES6 language mechanisms. The following code demonstrates how that works.

    class IterableArguments {
        constructor(...args) {
            this.args = args;
        }
        * [Symbol.iterator]() {
            for (let arg of this.args) {
                yield arg;
            }
        }
    }
    
    for (let x of new IterableArguments('hello', 'world')) {
        console.log(x);
    }
    
    // Output:
    // hello
    // world

Class expressions

Similarly to functions, there are both class declarations and class expressions. Also similarly, the identifier of a class expression is only visible within the expression:

    const MyClass = class Me {
        getClassName() {
            return Me.name;
        }
    };
    let inst = new MyClass();
    console.log(inst.getClassName()); // Me
    console.log(Me.name); // ReferenceError: Me is not defined

Static properties

Given a class Foo, we distinguish two kinds of properties:

  • The prototype properties of Foo are the properties of Foo.prototype. They are usually methods and inherited by instances of Foo.
  • The static properties (or class properties) of Foo are the properties of Foo itself.

The prototype properties defined inside the body of a class are all methods. If you prefix one of those method definitions with the keyword static, you create a class method:

    class Foo {
        static classMethod() {
            return 'hello';
        }
    }
    Foo.classMethod(); // 'hello'

Subclassing

The extends clause lets you create a subclass of an existing constructor (which may or may not have been defined via a class):

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString () {
            return '(' + this.x + ', ' + this.y + ')';
        }
    }
    
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y);
            this.color = color;
        }
        toString () {
            return super.toString() + ' in ' + this.color;
        }
    }

Again, this class is used like you’d expect:

    > let cp = new ColorPoint(25, 8, 'green');
    > cp.toString()
    '(25, 8) in green'
    
    > cp instanceof ColorPoint
    true
    > cp instanceof Point
    true

Point is called a base class, because it doesn’t have an extends clause. ColorPoint is called a derived class.

The prototype of a subclass is the superclass

The prototype of a subclass is the superclass in ECMAScript 6:

    > Object.getPrototypeOf(ColorPoint) === Point
    true

That means that static properties are inherited:

    class Foo {
        static classMethod() {
            return 'hello';
        }
    }
    
    class Bar extends Foo {
    }
    Bar.classMethod(); // 'hello'
Super-constructor calls

In a derived class, you must call super() before you can use this:

    class Foo {}
    
    class Bar extends Foo {
        constructor(num) {
            let tmp = num * 2; // OK
            this.num = num; // ReferenceError
            super();
            this.num = num; // OK
        }
    }

Implicitly leaving a derived constructor without calling super() also causes an error:

    class Foo {}
    
    class Bar extends Foo {
        constructor() {
        }
    }
    
    let bar = new Bar(); // ReferenceError
Default constructors for classes

If you don’t specify a constructor for a base class, the following definition is used:

    constructor() {}

For derived classes, the following default constructor is used:

    constructor(...args) {
        super(...args);
    }

Subclassing built-in constructors

In ECMAScript 6, you can finally subclass all built-in constructors (there are work-arounds for ES5, but these have significant limitations).

For example, you can now create your own exception classes (that will inherit the feature of having a stack trace in most engines):

    class MyError extends Error {    
    }
    throw new MyError('Something happened!');

You can also create subclasses of Array whose instances properly handle length:

    class MyArray extends Array {
        constructor(len) {
            super(len);
        }
    }
    
    // Instances of of `MyArray` work like real arrays:
    let myArr = new MyArray(0);
    console.log(myArr.length); // 0
    myArr[0] = 'foo';
    console.log(myArr.length); // 1

Note that subclassing built-in constructors is something that engines have to support natively, you won’t get this feature via transpilers.

Overriding the result of a constructor

Just like in ES5, you can override the result of a constructor by explicitly returning an object:

    class Foo {
        constructor() {
            return Object.create(null);
        }
    }
    console.log(new Foo() instanceof Foo); // false

The details of classes

What we have seen so far are the essentials of classes. You only need to read on if you are interested how things happen under the hood. Let’s start with the syntax of classes. The following is a slightly modified version of the syntax shown in Sect. A.4 of the ECMAScript 6 specification.

    ClassDeclaration:
        "class" BindingIdentifier ClassTail
    ClassExpression:
        "class" BindingIdentifier? ClassTail
    
    ClassTail:
        ClassHeritage? "{" ClassBody? "}"
    ClassHeritage:
        "extends" AssignmentExpression
    ClassBody:
        ClassElement+
    ClassElement:
        MethodDefinition
        "static" MethodDefinition
        ";"
    
    MethodDefinition:
        PropName "(" FormalParams ")" "{" FuncBody "}"
        "*" PropName "(" FormalParams ")" "{" GeneratorBody "}"
        "get" PropName "(" ")" "{" FuncBody "}"
        "set" PropName "(" PropSetParams ")" "{" FuncBody "}"
    
    PropertyName:
        LiteralPropertyName
        ComputedPropertyName
    LiteralPropertyName:
        IdentifierName  /* foo */
        StringLiteral   /* "foo" */
        NumericLiteral  /* 123.45, 0xFF */
    ComputedPropertyName:
        "[" Expression "]"

Two observations:

  • The value to be extended can be produced by an arbitrary expression. Which means that you’ll be able to write code such as the following:
          class Foo extends combine(MyMixin, MySuperClass) {}
    
  • Semicolons are allowed between methods.

Various checks

  • Error checks: the class name cannot be eval or arguments; duplicate class element names are not allowed; the name constructor can only be used for a normal method, not for a getter, a setter or a generator method.
  • Classes can’t be function-called. They throw a TypeException if they are.
  • Prototype methods cannot be used as constructors:
          class C {
              m() {}
          }
          new C.prototype.m(); // TypeError
    

Attributes of properties

Class declarations create (mutable) let bindings. For a given class Foo:

  • Static methods Foo.* are writable and configurable, but not enumerable. Making them writable allows for dynamic patching.
  • A constructor and the object in its property prototype have an immutable link:
    • Foo.prototype is non-writeable, non-enumerable, non-configurable.
    • Foo.prototype.constructor is non-writeable, non-enumerable, non-configurable.
  • Prototype methods Foo.prototype.* are writable and configurable, but not enumerable.

Note that method definitions in object literals produce enumerable properties.

The details of subclassing

Subclassing in ECMAScript 5

Let’s review how one does subclassing in ECMAScript 5:

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    ···
    
    // Allocate instance here
    function ColorPoint(x, y, color) {
        Point.call(this, x, y); // (A)
        this.color = color;
    }
    ColorPoint.prototype = Object.create(Point.prototype); // (B)
    ···
    
    var cp = new ColorPoint(25, 8, 'green');

You want to inherit two things:

  • The instance properties of Point are inherited by calling it while setting this to the current instance of ColorPoint (line A). That leads to Point adding its instance properties to that instance.
  • The prototype properties in Point.prototype are inherited by making it the prototype of ColorPoint.prototype (line B).

The following diagram shows what objects exist after creating cp in line C.

[In order to keep things simple, I’ve omitted two things from the diagram that are not essential for understanding what is going on. First, Point is a sub-constructor of Object (its prototype is Object.prototype), as all constructors are, by default. Second, Point and ColorPoint are both instances of Function (they have the same prototype object, Function.prototype).]

Tip for understanding this diagram: [[Prototype]] is an inheritance relationship between objects, while prototype is a normal property whose value is an object. The property prototype is only special because the new operator makes its value the prototype of every instance it creates.

Creating cp is all about setting up the prototype chain shown in the right column. This prototype chain determines what properties cp has. The constructors contribute to the chain in two ways: First, they add own properties to cp. Second, the objects pointed to by their prototype properties become members of the chain (or rather, ColorPoint.prototype becomes the prototype object of cp).

Subclassing in ECMAScript 6

In ECMAScript 6, subclassing looks as follows.

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        ···
    }
    
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y);
            this.color = color;
        }
        ···
    }
    
    let cp = new ColorPoint(25, 8, 'green');

The result is similar to what the ES5 code produced.

Even though the result is similar, ES6 gets there differently. This is an approximation of what goes on under the hood:

    // Allocate instance here
    function Point(x, y) {
        this = Object.create(new.target);
        this.x = x;
        this.y = y;
    }
    
    function ColorPoint(x, y, color) {
        this = Reflect.construct(Point, [x, y], new.target); // (A)
        this.color = color;
    }
    Object.setPrototypeOf(ColorPoint, Point);
    
    let cp = Reflect.construct(ColorPoint, [25, 8], ColorPoint); // (B)

Constructors now have an implicit parameter new.target that is originally filled in by the new operator (line B) and passed on by super (line A). Reflect.construct() [4] lets you do a constructor-call while specifying new.target via the last parameter.

Therefore, ES6 does two things quite differently.

First, the prototype of ColorPoint is Point. That means that ColorPoint inherits all of Point‘s properties.

Second, if the new operator constructor-calls the first in a chain of constructors (where derived constructors make super-constructor calls until execution reaches a base constructor) then ES6 and ES6 behave differently:

  • In ES5, the first in a chain of constructors allocates an instance and passes it on to its super-constructor. This continues until a base constructor is reached.
  • In ES6, the last in a chain of constructors allocates an instance. This happens as follows. this is uninitialized when entering a derived constructor. super() constructor-calls the super-constructor (and later initializes this with the result). This continues until execution reaches a base constructor, which allocates the instance, setting its prototype to new.target.

The advantage of the new approach is that it enables normal code to subclass built-in constructors (such as Error and Array).

This was a short explanation of ES6 subclassing. I’ll explain it more thoroughly later on.

Making super-calls in methods

The following ES5 code makes a super-call in line (A).

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype.toString = function () {
        return '(' + this.x + ', ' + this.y + ')';
    };
    
    function ColorPoint(x, y, color) {
        Point.call(this, x, y);
        this.color = color;
    }
    ColorPoint.prototype = Object.create(Point.prototype);
    ColorPoint.prototype.toString = function () {
        return Point.prototype.toString.call(this) // (A)
               + ' in ' + this.color;
    };
    
    var cp = new ColorPoint(25, 8, 'green');
    console.log(cp.toString()); // (25, 8) in green

The same code looks as follows in ECMAScript 6.

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString () { // (A)
            return '(' + this.x + ', ' + this.y + ')';
        }
    }
    
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y);
            this.color = color;
        }
        toString () {
            return super.toString() // (B)
                   + ' in ' + this.color;
        }
    }
    
    let cp = new ColorPoint(25, 8, 'green');
    console.log(cp.toString()); // (25, 8) in green

To understand how super-calls work, let’s look at the object diagram of cp:

ColorPoint.prototype.toString makes a super-call (line B) to the method (starting in line A) that it has overridden. Let’s call the object, in which a method is stored, the home object of that method. For example, ColorPoint.prototype is the home object of ColorPoint.prototype.toString().

The super-call in line B involves three steps:

  1. Start your search in the prototype of the home object of the current method.
  2. Look for a method whose name is toString. That method may be found in the object where the search started or later in the prototype chain.
  3. Call that method with the current this. The reason for doing so is: the super-called method must be able to access the same instance properties (in our example, the properties of cp).

Let’s express these steps in three different, but equivalent, ways:

    // Variation 1
    var result = Point.prototype.toString.call(this) // steps 1,2,3
    
    // Variation 2
    var superObject = Point.prototype; // step 1
    var superMethod = superObject.toString; // step 2
    var result = superMethod.call(this) // step 3
    
    // Variation 3
    var homeObject = ColorPoint.prototype;
    var superObject = Object.getPrototypeOf(homeObject); // step 1
    var superMethod = superObject.toString; // step 2
    var result = superMethod.call(this) // step 3

Variation 3 is how ECMAScript 6 handles super-calls. This approach is supported by two internal bindings that the environments of functions have (environments provide storage space, so-called bindings, for the variables in a scope):

  • [[thisValue]]: You already know this internal binding, it also exists in ECMAScript 5 and stores the value of this.
  • [[HomeObject]]: Refers to the home object of the environment’s function. Filled in via an internal property [[HomeObject]] that all methods have that use super. Both the binding and the property are new in ECMAScript 6.

A method definition in a class literal that uses super is now special: Its value is still a function, but it has the internal property [[HomeObject]]. That property is set up by the method definition and can’t be changed in JavaScript. Therefore, you can’t meaningfully move such a method to a different object.

Using super to refer to a property is not allowed in function declarations, function expressions and generator functions. They are still allowed in method definitions inside object literals, but that may still change. Using super in an arrow function is the same as using it in the surrounding function or method.

The ES6 way of calling super-constructors

The following ES6 code makes a super-constructor call in line (A).

    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y); // (A)
            ···
        }
        ···
    }

This way of using super is only available in construct of derived classes (Sect. 14.5.1 in the spec). It works completely differently from the canonical way of subclassing in ES5. Before we examine how it works, let us first understand why you can’t subclass built-in constructors in ES5.

The problem with ES5 subclassing

In ECMAScript 5, most built-in constructors can’t be subclassed (several work-arounds exist).

To understand why, let’s use the canonical ES5 pattern to subclass Array. As we shall soon find out, this doesn’t work.

    function MyArray(len) {
        Array.call(this, len); // (A)
    }
    MyArray.prototype = Object.create(Array.prototype);

Unfortunately, if we instantiate MyArray, we find out that it doesn’t work properly: The instance property length does not change in reaction to us adding array elements:

    > var myArr = new MyArray(0);
    > myArr.length
    0
    > myArr[0] = 'foo';
    > myArr.length
    0

There are two obstracles that prevent myArr from being a proper array.

First obstacle: initialization. The this you hand to the constructor Array (in line A) is completely ignored. That means you can’t use Array to set up the instance that was created for MyArray.

    > var a = [];
    > var b = Array.call(a, 3);
    > a !== b  // a is ignored, b is a new object
    true
    > b.length // set up correctly
    3
    > a.length // unchanged
    0

Second obstacle: allocation. The instance objects created by Array are exotic (a term used by the ECMAScript specification for objects that have features that normal objects don’t have): Their property length tracks and influences the management of array elements. In general, exotic objects can be created from scratch, but you can’t convert an existing normal object into an exotic one. Unfortunately, that is what Array would have to do, when called in line A: It would have to turn the normal object created for MyArray into an exotic array object.

The solution: ES6 subclassing

In ECMAScript 6, subclassing Array looks as follows:

    class MyArray extends Array {
        constructor(len) {
            super(len);
        }
    }

This works (but it’s not something that ES6 transpilers can support, it depends on whether a JavaScript engine supports it natively):

    > let myArr = new MyArray(0);
    > myArr.length
    0
    > myArr[0] = 'foo';
    > myArr.length
    1

In ES6, super-constructor calls make use of two internal bindings of function environments (where the variables of function scopes are stored):

  • [[NewTarget]] is an implicit parameter of constructors (similar to the implicit parameter this of methods). It refers to the operand of the new operator that led to the current constructor call. In functions that weren’t constructor-called, its value is undefined.
  • [[FunctionObject]] refers to the function that is currently being executed.

So how does ES6 enable subclassing of built-in constructors? Classes that have an extends clause produce derived constructors and those handle object allocation differently from normal constructors (base constructors):

  • When a derived constructor is entered, its this is uninitialized. That means that getting or setting this leads to a ReferenceError.
  • If the constructor calls super() then that triggers a constructor call to the super-constructor, the result of that call is used to initialize this.

The new operator calls the first derived constructor and sets [[NewTarget]] to that constructor. Afterwards, super() passes [[NewTarget]] on to the next constructor. There may be a whole chain of derived constructors. Eventually, the constructor calls reach a base constructor:

  • Before execution enters a base constructor, a fresh object is created whose prototype is [[NewTarget]].prototype. this is set to that object when entering the constructor.
  • Built-in constructors override the default mechanism and return an exotic object. But the prototype of that object is still [[NewTarget]].prototype.

We can now see how the new approach of subclassing circumvents the obstacles:

  • Allocation happens in the base constructor, which means that Array can allocate an exotic object. While most of the new approach is due to how derived constructors behave, this step requires that a base constructor is aware of [[NewTarget]] and makes [[NewTarget]].prototype the protoype of the allocated instance.
  • Initialization also happens in the base constructor, a derived constructor receives an initialized object and works with that one instead of passing its own instance to the super-constructor and requiring it to set it up.
new.target

The internal variable [[NewTarget]] is available as new.target in ES6. Therefore, what a derived constructor such as MyArray does, looks roughly as follows.

    function MyArray(len) {
        this = Reflect.construct(Array, [len], new.target);
        // If this constructor is invoked via `new TargetConstr(···)
        // then the prototype of `this` is `TargetConstr.prototype`.
    }

Reflect.construct() [4] performs a constructor call. Its last parameter is the new-target. That is, MyArray passes its new-target on and can be subclassed, too.

Two facts about new.target:

  • new.target is available in all functions. It is undefined during a function call (as opposed to a constructor call). Therefore, new.target lets you determine whether a function was constructor-called or not.
  • new.target in arrow functions is the [[NewTarget]] of the surrounding (non-arrow) function or method.
Safety checks
  • this originally being uninitialized in derived constructors means that an error is thrown if they access this in any way before they have called super().
  • Once this is initialized, calling super() produces a ReferenceError. This protects you against calling super() twice.
  • If a constructor returns implicitly (without a return statement), the result is this. If this is uninitialized, a ReferenceError is thrown. This protects you against forgetting to call super().
  • If a constructor explicitly returns a non-object (including undefined and null), the result is this (this behavior is required to remain compatible with ES5 and earlier). If this is uninitialized, a TypeError is thrown.
  • If a constructor explicitly returns a non-object, it is used as its result. Then it doesn’t matter whether this is initialized or not.
The extends clause

Let’s examine how the extends clause influences how a class is set up (Sect. 14.5.14 of the spec).

The value of an extends clause must be “constructible” (invocable via new). null is allowed, though.

    class C {
    }
  • Constructor kind: base
  • Prototype of C: Function.prototype (like a normal function)
  • Prototype of C.prototype: Object.prototype (which is also the prototype of objects created via object literals)
    class C extends B {
    }
  • Constructor kind: derived
  • Prototype of C: B
  • Prototype of C.prototype: B.prototype
    class C extends Object {
    }
  • Constructor kind: derived
  • Prototype of C: Object
  • Prototype of C.prototype: Object.prototype

Note the following subtle difference with the first case: If there is no extends clause, the class is a base class and allocates instances. If a class extends Object, it is a derived class and Object allocates the instances. The resulting instances (including their prototype chains) are the same, but you get there differently.

    class C extends null {
    }
  • Constructor kind: derived
  • Prototype of C: Function.prototype
  • Prototype of C.prototype: null

Such a class is not very useful: new-calling it leads to an error, because the default constructor makes a super-constructor call and Function.prototype (the super-constructor) can’t be constructor-called. The only way to make the error go away is by adding a constructor that returns an object.

Constructor calls explained via JavaScript code

The JavaScript code in this section is a much simplified version of how the specification describes constructor calls and super-constructor calls. It may be interesting to you if you prefer code to explanations in human language. Before we can delve into the actual functionality, we need to understand a few other mechanisms.

Internal variables and properties

The specification writes internal variables and properties in double brackets ([[Foo]]). In the code, I use double underscores, instead (__Foo__).

Internal variables used in the code:

  • [[NewTarget]]: The operand of the new operator that triggered the current constructor call (passed on if [[Construct]] is called recursively via super()).
  • [[thisValue]]: Stores the value of this.
  • [[FunctionObject]]: Refers to the function that is currently executed.

Internal properties used in the code:

  • [[Construct]]: All constructor functions (including those created by classes) have this own (non-inherited) method. It implements constructor calls and is invoked by new.
  • [[ConstructorKind]]: A property of constructor functions whose value is either 'base' or 'derived'.

Environments

Environments provide storage space for variables, there is one environment per scope. Environments are managed as a stack. The environment on top of that stack is considered active. The following code is a sketch of how environments are handled.

    /**
     * Function environments are special, they have a few more
     * internal variables than other environments.
     * (`Environment` is not shown here)
     */
    class FunctionEnvironment extends Environment {
        constructor(Func) {
            // [[FunctionObject]] is a function-specific
            // internal variable
            this.__FunctionObject__ = Func;
        }    
    }
    
    /**
     * Push an environment onto the stack
     */
    function PushEnvironment(env) { ··· }
    
    /**
     * Pop the topmost environment from the stack
     */
    function PopEnvironment() { ··· }
    
    /**
     * Find topmost function environment on stack
     */
    function GetThisEnvironment() { ··· }

Constructor calls

Let’s start with the default way (ES6 spec Sect. 9.2.3) in which constructor calls are handled for functions:

    /**
     * All constructible functions have this own method,
     * it is called by the `new` operator
     */
    AnyFunction.__Construct__ = function (args, newTarget) {
        let Constr = this;
        let kind = Constr.__ConstructorKind__;
    
        let env = new FunctionEnvironment(Constr);
        env.__NewTarget__ = newTarget;
        if (kind === 'base') {
            env.__thisValue__ = Object.create(newTarget.prototype);
        } else {
            // While `this` is uninitialized, getting or setting it
            // throws a `ReferenceError`
            env.__thisValue__ = uninitialized;
        }
    
        PushEnvironment(env);
        let result = Constr(...args);
        PopEnvironment();
    
        // Let's pretend there is a way to tell whether `result`
        // was explicitly returned or not
        if (WasExplicitlyReturned(result)) {
            if (isObject(result)) {
                return result;
            }
            // Explicit return of a primitive
            if (kind === 'base') {
                // Base constructors must be backwards compatible
                return env.__thisValue__; // always initialized!
            }
            throw new TypeError();
        }
        // Implicit return
        if (env.__thisValue__ === uninitialized) {
            throw new ReferenceError();
        }
        return env.__thisValue__;
    }

Super-constructor calls

Super-constructor calls are handled as follows (ES6 spec Sect. 12.3.5.1).

    /**
     * Handle super-constructor calls
     */
    function super(...args) {
        let env = GetThisEnvironment();
        let newTarget = env.__NewTarget__;
        let activeFunc = env.__FunctionObject__;
        let superConstructor = Object.getPrototypeOf(activeFunc);
    
        env.__thisValue__ = superConstructor
                            .__Construct__(args, newTarget);
    }

The species pattern

One more mechanism of built-in constructors has been made extensible in ECMAScript 6: If a method such as Array.prototype.map() returns a fresh instance, what constructor should it use to create that instance? The default is to use the same constructor that created this, but some subclasses may want it to remain a direct instance of Array. ES6 lets subclasses override the default, via the so-called species pattern:

  • When creating a new instance of Array, methods such as map() use the constructor stored in this.constructor[Symbol.species].
  • If a sub-constructor of Array does nothing, it inherits Array[Symbol.species]. That property is a getter that returns this.

You can override the default, via a static getter (line A):

    class MyArray1 extends Array {
    }
    let result1 = new MyArray1().map(x => x);
    console.log(result1 instanceof MyArray1); // true
    
    class MyArray2 extends Array {
        static get [Symbol.species]() { // (A)
            return Array;
        }
    }
    let result2 = new MyArray2().map(x => x);
    console.log(result2 instanceof MyArray2); // false

An alternative is to use Object.defineProperty() (you can’t use assignment, as that would trigger a setter, which doesn’t exist):

    Object.defineProperty(
        MyArray2, Symbol.species, {
            value: Array
        });

The following getters all return this, which means that methods such as Array.prototype.map() use the constructor that created the current instance for their results.

  • Array.get [Symbol.species]()
  • ArrayBuffer.get [Symbol.species]()
  • Map.get [Symbol.species]()
  • Promise.get [Symbol.species]()
  • RegExp.get [Symbol.species]()
  • Set.get [Symbol.species]()
  • %TypedArray%.get [Symbol.species]()

Conclusion

The specialization of functions

There is an interesting trend in ECMAScript 6: Previously, a single kind of function took on three roles: real function, method and constructor. In ES6, there is specialization:

  • Arrow functions are specialized for non-method callbacks, where them picking up the this of their surrounding method or constructor is an advantage. Without this, they don’t make much sense as methods and they throw an exception when invoked via new.
  • Method definitions enable the use of super, by setting up the property [[HomeObject]]. The functions they produce can’t be constructor-called.
  • Class definitions are the only way to create derived constructors (enabling ES6-style subclassing that works for built-in constructors). Class definitions produce functions that can only be constructor-called.

The future of classes

The design maxim for classes was “maximally minimal”. Several advanced features were discussed, but ultimately discarded in order to get a design that would be unanimously accepted by TC39.

Upcoming versions of ECMAScript can now extend this minimal design – classes will provide a foundation for features such as traits (or mixins), value objects (where different objects are equal if they have the same content) and const classes (that produce immutable instances).

Does JavaScript need classes?

Classes are controversial within the JavaScript community. On one hand, people coming from class-based languages are happy that they don’t have to deal with JavaScript’s unorthodox inheritance mechanisms, anymore. On the other hand, there are many JavaScript programmers who argue that what’s complicated about JavaScript is not prototypal inheritance, but constructors [5].

ES6 classes provide a few clear benefits:

  • They are backwards compatible with much of the current code.
  • Compared to constructors and constructor inheritance, classes make it easier for beginners to get started.
  • Subclassing is supported within the language.
  • Built-in constructors are subclassable.
  • No library for inheritance is needed, anymore; code will become more portable between frameworks.
  • They provide a foundation for advanced features in the future (mixins and more).
  • They help tools that statically analyze code (IDEs, type checkers, style checkers, etc.).

I have made my peace with classes and am glad that they are in ES6. I would have preferred them to be prototypal (based on constructor objects [5], not constructor functions), but I also understand that backwards compatibility is important.

Further reading

Acknowledgement: #1 was an important source of this blog post.

  1. Instantiation Reform: One last time”, slides by Allen Wirfs-Brock.
  2. Exploring ES6: Upgrade to the next version of JavaScript”, book by Axel
  3. Iterators and generators in ECMAScript 6
  4. Meta programming with ECMAScript 6 proxies
  5. Prototypes as classes – an introduction to JavaScript inheritance

Source:: 2ality

Standardizing (a flavor of) Markdown

By Axel Rauschmayer

Update 2014-09-05: Jeff Atwood renames “Standard Markdown” to “Common Markdown” and apologizes to John Gruber. Details: “Standard Markdown is now Common Markdown”.

On September 3, Jeff Atwood announced a new standardization effort for John Gruber’s Markdown: Standard Markdown.

It is amazing how ubiquitous Markdown has become and it’s great that there is now a standard for it. Highlights:

  • The working group comprises representatives from: GitHub, Reddit, Stack Exchange, the open source community.
  • There is a proper specification that also describes a parsing strategy. This should help tremendously with writing a parser that can handle all content that complies with the standard. Given all the incompatible Markdown dialects in existence, that is currently a very difficult task.
  • There are reference implementations in JavaScript and C and a validation test suite.
    • You can try out the reference implementation online.

Background:

A few more thoughts:

  • The use case “publishing” is currently a bit underrepresented in the working group. Members of the Ghost blogging platform and of Leanpub would be great additions.
  • Mid-term to long-term, I’d like a more extensive standard to build on this one: It should comprise the Asciidoc features that are currently missing from Markdown (but maybe in more of a formal syntax instead of something ASCII art-ish). Rationale: better support Markdown for publishing, especially books.

Source:: 2ality

30 Amazing Games Made Only With HTML5

By Danny Markov

30-amazing-games-only-with-html5

Browsers and JavaScript are constantly getting more powerful and fully featured. There was a time when is building any type of game required Flash. But with this out of the way, the stage is set for powerful HTML5 and WebGL gaming! Here are 30 of our favorite games which run in all modern browsers and are build only with web technologies.

1. HexGL

Genre: Arcade, Racing

HexGL

HexGL is a futuristic, fast-paced racing game built on HTML5, JavaScript and WebGL. You can control a space ship by using your keyboard, a touchscreen device or even a leap motion controller if you have one.

HexGL

2. CrossCode

Genre: Action, RPG

Cross Code

Cross Code

A retro-inspired 2D game set in the distant future. This one is full of great game mechanics such as combos, puzzles, skill trees, quests, items and more.

3. Sketchout

Genre: Arcade

Sketchout

Sketchout

The objective of Sketchout is to protect your planet and destroy the opposition by deflecting meteors as you control an Breakout-style paddle and draw lines at the same time. Design is where this game shines with awesome visuals and music.

4. Treasure Arena

Genre: Multiplayer, RPG, Action

Treasure Arena

Treasure Arena

Treasure Arena is a dynamic battle-arena game for up to 4 players built with the power of socket.io. It features different game modes, excellent framerate and a great soundtrack. A very fun game.

5. Bejeweled

Genre: Arcade, Puzzle,Relaxing

Bejeweled

Bejeweled

The classic Bejeweled game in HTML5 form. This is an official clone and as such it runs and looks perfectly. The ultimate time killer.

6. Missile Game

Genre: Arcade

Missile Game

Missile Game

A very challenging game in which you play as a missile being lunched into a tunnel. The game has cool black and white graphics that are nicely used to create a strong dept of field effect.

7. Gods Will Be Watching

Genre: Puzzle

Gods Will Be Watching

Gods Will Be Watching

You and your crew have to survive for 40 days in isolation in this creepy (but awesome) game. There are six members of your team including a dog, a psychiatrist and a robot and you have to interact with them the right way to keep them warm, fed and sane.

8. Sinuous

Genre: Arcade

Sinuous

Sinuous

A simple game with minimalistic graphics and a fluid frame rate. Avoid colliding with the red dots while picking up power-ups. Also, never stop moving around if you want those extra points!

9. Swooop

Genre: Arcade

Swooop

Swooop

Fly around and collect gems and stars in a beautiful and colorful 3D world.

10. Free Rider HD

Genre: Arcade, Racing

Free Rider HD

Free Rider HD

Free Rider HD is an addicting game where you race a bike on tracks drawn by other players. You can play on any of the thousands of player made tracks or create your own and share it.

11. Entanglement

Genre: Puzzle, Relaxing

Entanglement

Entanglement

The point of this game is to create a path as long as possible by placing segments on a grid. You can play alone on one of the many levels or play against friends.

12. Escape from XP

Genre: Action, Arcade

Escape From XP

Escape From XP

Celebrate the end of Windows XP support with Escape from XP. It’s your job to rescue the last developer trapped in Clippy’s tyranny. Fight to survive endless waves of XP enemies then finish off the OS with a bang.

13. Polycraft

Genre: RPG, Tower Defense, Action

Polycraft

Polycraft

In this awesome 3D game you run around collecting resources, building stuff, completing quests and fighting stuff. Everything about it is polished and it runs perfectly smooth.

14. 2048

Genre: Puzzle

2048

2048

A very addictive game that you’ve probably already played. In 2048 you move numbered tiles around and merge them. Get that elusive 2018 tile to win!

15. Onslaught Arena

Genre: Action

Onslaught Arena

Onslaught Arena

A fast-paced retro styled survival game where you fight off hordes of enemies using different weapons.

16. Angry Birds

Genre: Puzzle

Angry Birds

Angry Birds

The (once) popular Angry Birds game in HTML5, so you can play it in your browser.

17. Cube Slam

Genre: Arcade, Multiplayer

Cube Slam

Cube Slam

The classic pong game done with fun colors and cool 3D graphics. You can challenge a friend by just sending them a URL and if you want to, you can see each other via webcam.

18. The Wizard

Genre: Action, RPG, Strategy

The WIzard

The WIzard

The Wizard is a turn-based dungeon crawler where you’ll encounter mythical monsters and find marvellous spells. The game features cool combat mechanics and can be quite challanging at times.

19. X-Type

Genre: Action, Arcade

X-Type

X-Type

Survive as many bossfights as you can in this cool looking space shooter.

20. Cookie Clicker

Genre: Casual, Funny

Cookie Clicker

Cookie Clicker

Cookie clicker is a game that was probably created as a joke but offers tremendous amounts of fun nonetheless. You start off with 0 cookies and after some productive cookie clicking you will find yourself with billions of cookies to spare.

21. Elevator Saga

Genre: Puzzle, Coding

Elevator Saga

Elevator Saga

And here is something for programmer-types. Your task in Elevator Saga is to transport people in the most efficient manner by programming the movement of elevators. Just one little thing – every move you make is done with JavaScript.

22. Game of Bombs

Genre: Action, RGP, Multiplayer

Game Of Bombs

Game Of Bombs

Game of Bombs is a bomberman type game placed in a vast map full of enemy players. Collect power-ups, skins and achievements in your way to becomming the best bomberman player.

23. Olympia Rising

Genre: Platformer, Action

Olympia Rising

Olympia Rising

A dynamic platformer with nice retro looking graphics. It is set in ancient Greece, where you play as a woman who is given another chance at life, and has to escape from the world of the dead.

24. Pixel Race

Genre: Arcade, Racing

Pixel Race

Pixel Race

A game with awesome frame rates and a simple concept, in which you control a car to avoid obstacles, while collecting coins. If you have the patience and the free time you might become the best in the world (the record is 36309 coins).

25. Little Alchemy

Genre: Puzzle

Little Alchemy

Little Alchemy

Start off with the four basic elements and combine them to create the 510 possible combinations.

26. Arena5

Genre: Arcade

Arena 5

Arena 5

Fly around a digital field and shoot geometrical enemies to get a high score.

27. Vector Runner Remix

Genre: Arcade

Vector Runner Remix

Vector Runner Remix

Make it as far as you can in this platformer full of colors and geometrical shapes.

28. Biolab Disaster

Genre: Action, Platformer

Biolab Disaster

Biolab Disaster

An awesome pixel art platformer where you have to escape a lab full of mutated creatures and other baddies.

29. World’s Biggest PAC-MAN

Genre: Arcade

World's Biggest Pacman

World’s Biggest Pacman

A huge collection of PAC-MAN mazes – probably more then you can beat in your lifetime (this isn’t a challenge, please don’t try).

30. New Super Resident Raver

Genre: Action, Arcade

New Super Resident Raver

New Super Resident Raver

Save panicking people from the incoming zombie invasion. Collect money, upgrade your weapons and fight zombies.

To Wrap it Up

And this concludes our list of HTML5 games! They are all fun and have huge time wasting potential. Some of them don’t have sound, but frankly they don’t need it. Do you have a favorite HTML5 game that is not included in this list? Share it in our comment section.

Source:: Tutorialzine.com

Tutorial: Making a Shoutbox with PHP and jQuery

By Nick Anastasov

shoutbox-php-jquery

In this tutorial, we are going to build a shout box with PHP and jQuery, which allows visitors of your website to leave short comments to one another. Shouts will be stored on the server as files, no database like MySQL will be required. We are going to use two PHP libraries to make things easier – Flywheel for storing the shouts as json files and RelativeTime for creating human readable relative time stamps. We will be using Composer to install these libraries.

On the client side, we are using plain jQuery code, and the Emoji One library, which is a free project and library for adding pretty emojis to web apps. Let’s begin!

Running the shoutbox

You can grab the source code from the download button above. It has plenty of comments and is easy to follow. To run it, simply upload it to your web hosting space or add it to the apache htdocs folder if you run something like XAMPP or MAMP. Then, open http://localhost in your browser (or your website, if you uploaded it to your hosting space). Here are a few things to look for:

  • The zip files already contains the dependencies, so you don’t need to install Composer. This makes it easy to get started with the code – simply upload it and use it!
  • Make sure that the data/shouts directory exists and is writable. Otherwise you will see errors in your log file and no shouts will be stored. You might need to chmod it to 777 if you keep seeing errors.

The HTML

Let’s start with index.html. It is a regular HTML5 document, which includes our JavaScript libraries, scripts and stylesheets. Here are the parts relevant to the shoutbox:

index.html

<div class="shoutbox">
    
    <h1>Shout box <img src='./assets/img/refresh.png'/></h1>
    
    <ul class="shoutbox-content"></ul>
    
    <div class="shoutbox-form">
        <h2>Write a message <span>×</span></h2>
        
        <form action="./publish.php" method="post">
            <label for="shoutbox-name">nickname </label> <input type="text" id="shoutbox-name" name="name"/>
            <label class="shoutbox-comment-label" for="shoutbox-comment">message </label> <textarea id="shoutbox-comment" name="comment" maxlength='240'></textarea>
            <input type="submit" value="Shout!"/>
        </form>
    </div>
    
</div>

With JavaScript we will insert the published shouts into the

    element. The form is hidden by default, and only revealed when the “Write a message” header is clicked.

    Shoutbox with PHP and jQuery

    The JavaScript Code

    And here is our script.js, which makes the above HTML work:

    assets/js/script.js

    $(function(){
    
        // Storing some elements in variables for a cleaner code base
    
        var refreshButton = $('h1 img'),
            shoutboxForm = $('.shoutbox-form'),
            form = shoutboxForm.find('form'),
            closeForm = shoutboxForm.find('h2 span'),
            nameElement = form.find('#shoutbox-name'),
            commentElement = form.find('#shoutbox-comment'),
            ul = $('ul.shoutbox-content');
    
        // Replace :) with emoji icons:
        emojione.ascii = true;
    
        // Load the comments.
        load();
        
        // On form submit, if everything is filled in, publish the shout to the database
        
        var canPostComment = true;
    
        form.submit(function(e){
            e.preventDefault();
    
            if(!canPostComment) return;
            
            var name = nameElement.val().trim();
            var comment = commentElement.val().trim();
    
            if(name.length && comment.length && comment.length < 240) {
            
                publish(name, comment);
    
                // Prevent new shouts from being published
    
                canPostComment = false;
    
                // Allow a new comment to be posted after 5 seconds
    
                setTimeout(function(){
                    canPostComment = true;
                }, 5000);
    
            }
    
        });
        
        // Toggle the visibility of the form.
        
        shoutboxForm.on('click', 'h2', function(e){
            
            if(form.is(':visible')) {
                formClose();
            }
            else {
                formOpen();
            }
            
        });
        
        // Clicking on the REPLY button writes the name of the person you want to reply to into the textbox.
        
        ul.on('click', '.shoutbox-comment-reply', function(e){
            
            var replyName = $(this).data('name');
            
            formOpen();
            commentElement.val('@'+replyName+' ').focus();
    
        });
        
        // Clicking the refresh button will force the load function
        
        var canReload = true;
    
        refreshButton.click(function(){
    
            if(!canReload) return false;
            
            load();
            canReload = false;
    
            // Allow additional reloads after 2 seconds
            setTimeout(function(){
                canReload = true;
            }, 2000);
        });
    
        // Automatically refresh the shouts every 20 seconds
        setInterval(load,20000);
    
    
        function formOpen(){
            
            if(form.is(':visible')) return;
    
            form.slideDown();
            closeForm.fadeIn();
        }
    
        function formClose(){
    
            if(!form.is(':visible')) return;
    
            form.slideUp();
            closeForm.fadeOut();
        }
    
        // Store the shout in the database
        
        function publish(name,comment){
        
            $.post('publish.php', {name: name, comment: comment}, function(){
                nameElement.val("");
                commentElement.val("");
                load();
            });
    
        }
        
        // Fetch the latest shouts
        
        function load(){
            $.getJSON('./load.php', function(data) {
                appendComments(data);
            });
        }
        
        // Render an array of shouts as HTML
        
        function appendComments(data) {
    
            ul.empty();
    
            data.forEach(function(d){
                ul.append('<li>'+
                    '<span class="shoutbox-username">' + d.name + '</span>'+
                    '<p class="shoutbox-comment">' + emojione.toImage(d.text) + '</p>'+
                    '<div class="shoutbox-comment-details"><span class="shoutbox-comment-reply" data-name="' + d.name + '">REPLY</span>'+
                    '<span class="shoutbox-comment-ago">' + d.timeAgo + '</span></div>'+
                '</li>');
            });
    
        }
    
    });

    The Emoji One library has version for both JavaScript and PHP. In the appendComments method, we use the emojione.toImage() function to convert all typed-out smileys into emoji. See all functions that are supported, and check out this handy emoji code website. Now that the frontend is ready, let’s move on to the backend.

    The PHP Code

    We have two files – publish.php and load.php. The first accepts a POST request for storing shouts in the data store, and the second returns the 20 latest shouts. These files are not opened directly by visitors – they only handle AJAX requests.

    publish.php

    <?php
    
    // Include our composer libraries
    require 'vendor/autoload.php';
    
    // Configure the data store
    
    $dir = __DIR__.'/data';
    
    $config = new JamesMossFlywheelConfig($dir, array(
        'formatter' => new JamesMossFlywheelFormatterJSON,
    ));
    
    $repo = new JamesMossFlywheelRepository('shouts', $config);
        
    // Store the posted shout data to the data store
    
    if(isset($_POST["name"]) && isset($_POST["comment"])) {
        
        $name = htmlspecialchars($_POST["name"]);
        $name = str_replace(array("n", "r"), '', $name);
    
        $comment = htmlspecialchars($_POST["comment"]);
        $comment = str_replace(array("n", "r"), '', $comment);
        
        // Storing a new shout
    
        $shout = new JamesMossFlywheelDocument(array(
            'text' => $comment,
            'name' => $name,
            'createdAt' => time()
        ));
        
        $repo->store($shout);
        
    }

    Here we directly use the Flywheel library we mentioned in the beginning. Once it is configured, you can store any type of data, which will be written as a JSON file in the data/shouts folder. Reading these shouts is done in load.php:

    load.php

    <?php
    
    require 'vendor/autoload.php';
    
    // If you want to delete old comments, make this true. We use it to clean up the demo.
    $deleteOldComments = false;
    
    // Setting up the data store
    
    $dir = __DIR__.'/data';
    
    $config = new JamesMossFlywheelConfig($dir, array(
        'formatter' => new JamesMossFlywheelFormatterJSON,
    ));
    
    $repo = new JamesMossFlywheelRepository('shouts', $config);
    
    // Delete comments which are more than 1 hour old if the variable is set to be true.
    
    if($deleteOldComments) {
        
        $oldShouts = $repo->query()
                    ->where('createdAt', '<', strtotime('-1 hour'))
                    ->execute();
    
        foreach($oldShouts as $old) {
            $repo->delete($old->id);
        }
        
    }
    
    // Send the 20 latest shouts as json
    
    $shouts = $repo->query()
            ->orderBy('createdAt ASC')
            ->limit(20,0)
            ->execute();
    
    $results = array();
    
    $config = array(
        'language' => 'RelativeTimeLanguagesEnglish',
        'separator' => ', ',
        'suffix' => true,
        'truncate' => 1,
    );
    
    $relativeTime = new RelativeTimeRelativeTime($config);
            
    foreach($shouts as $shout) {
        $shout->timeAgo = $relativeTime->timeAgo($shout->createdAt);
        $results[] = $shout;
    }
    
    header('Content-type: application/json');
    echo json_encode($results);

    We’ve included code which deletes shouts older than an hour. We use this feature to keep the demo clean. You can enable it if you wish. After selecting the shouts, we are also calculating the human-readable relative time stamp with the RelativeTime library.

    With this our shoutbox is ready! You can embed it in your website, customize it and change the code any way you please. We hope you like it!

    Source:: Tutorialzine.com

10 Things That Drive Me Mad When Visiting A Website

By Martin Angelov

10-things-that-drive-me-mad-when-visiting-a-website

There is a lot of hate on the internet. Most of the time, it is only because people find it easier to vent their real-life frustration online. But sometimes it is the websites you visit that drive you mad. Here are 10 usability failures that are guaranteed to piss your users off. If you are a web developer/designer, read the how to fix tips to make sure you are not part of the problem!

1. Forms that lose your input on error

As far as infuriating usability issues go, this has to rank at the top. You spend all that time filling in a form, making sure everything is perfect, and then, suddenly, all is gone forever. A habit that probably most of you have developed is to copy the contents of the field that took you the most time to fill, just in case everything goes to waste.

How to fix it:

If you are a web developer, simply add some JavaScript to your forms, use a validation library or submit via AJAX. Something that is a bit more involving, if you wish to keep the logic of your forms entirely in the server side, is to make sure that the contents of the inputs is populated again by placing everything in the session on submit.

2. Captchas

I am sure I am not the only one that hates them. Some of these horrible inventions are simply impossible to discern. Combine it with #1, and you get a maddening combination.

Don’t you hate captchas?

How to make it better:

Spam bots are getting more and more sophisticated, so some kind of proof that you’re human will still be required. Some captchas are better than others. reCAPTCHA only shows house numbers, so they are easy to guess by humans (and you also aid the correctness of Google Streetview).

3. Sending spam

Don’t you just hate it when a website tries to engage you by flooding you with useless, spammy emails that are impossible to unsubscribe from? I know I do.

You make my inbox hurt, LinkedIn.

You make my inbox hurt, LinkedIn.

How to fix it:

STOP SPAMMING. Also, close your LinkedIn account. Who needs that anyway.

4. Using negative setting names

Another hair-pulling mistake that web developers make, is to build settings panels with overly creative setting names. Don’t do this:

Negative settings are bad

What!?

How to fix it:

Aim for clarity and use simple phrasing. Use checkboxes for on/off. Prefer select boxes over radio groups for more than three options. Organize your settings in logically connected groups.

5. Long forms

Out of all the ways you could be spending your time online, I bet that filling out forms is the one you hate the most. Here is how I usually react when I see a long registration form:

What’s this!? I only wanted to try out your todo list!

How to fix it

Only ask for information you absolutely need. Even then, don’t do it during sign up, or you risk people leaving.

6. Interstitial ads

Those horrible ads are the first thing you see on some websites. Some of these ads don’t even let you dismiss them for a few seconds.

Nobody wants your mobile app!

Nobody wants your mobile app!

How to fix it

By using these ads you:

  • Make everybody hate you
  • Piss off your users. And what is the first thing a pissed off user does when they eventually visit the page they were headed to? They write a hate comment. That is right – you are breeding trolls.
  • Give people a reason to install AdBlock which in turn hurts all the hardworking web owners out there.

So don’t.

7. On close dialogs

I loathe these from the bottom of my heart. When I’ve made my mind that I don’t want to spend any more time on your website, and you still prompt me to stay once I close the tab, I am tempted to unleash 4chan upon you.

On close dialogs

I want to leave, damn it!

How to fix it:

Delete your website from the internet. You are a bad person.

8. Placing things where I don’t expect them to be

User interfaces should be logically organized. Related actions give people context and allow them to navigate your web app easily. So don’t move things around where they clearly don’t belong. Here is a horrible navigation menu:

Confusing interfaces

Tuesday is a great day to format your hard drive!

So first, people should create an event, then invite their friends, and finally format their hard drives. The perfect conclusion to a productive day!

Of course, this is a fictional example, but you get the point. To fix this category of issues:

  • Read a bit about UX and interface design. This will help you spot and fix usability problems.
  • Ask out friends or relatives to use your web apps while you observe. If they are confused, you have more work to do.

9. Sites broken on mobile

I remember the time when web designers couldn’t wait to drop the dreaded 1024×768 resolution that constrained their web sites. But just as this became a fact, mobile happened, and with it came all kinds of screen sizes that we have to support. Making a site responsive is not that hard to do. But if you don’t it will drive visitors away. This is bad:

Non-responsive sites

Quora clearly wants you to use their mobile app

How to fix:

For existing sites – add some media queries. This can go a long way towards being more usable on mobile. For new sites, you can go with a framework like Bootstrap, which has a responsive grid that is easy to use.

10. Paywalls

I realize that some sites offer quality content that can’t be supported with ads alone, so it makes a sane business decision to lock it up behind a pay wall. But boy can this drive you mad when you’ve been sent a link that you want to read.

Paywall

Paywall example

So there you have it, that is 10! What would you add?

Source:: Tutorialzine.com

The Languages And Frameworks That You Should Learn In 2015

By Martin Angelov

languages-frameworks-learn-2015

Last week, we asked you which were the languages and frameworks you were looking forward to learn in 2015. 47 of you replied, and here are your answers.

Languages / platforms

Node.js is the winner here, with PHP second, and JavaScript – third. There is an amazing community forming around Node.js, so it isn’t a surprise that a lot of you are excited about it. If you know JavaScript, you are already half the way to building web apps in Node.js.

This is only half of the picture. Here are the frameworks that our readers are looking forward to picking up.

Frameworks

AngularJS takes the lead in the frameworks category. Large companies and enterprises have adopted Angular, which drives the demand for coders skilled in the framework. The fact that it is backed by some of Google’s best engineers also helps it reach the top spot.

To help you make your choice, we’ve prepared an overview of the above technologies and more!

Here is what you should learn in 2015

Libraries and frameworks come and go, so it is risky to put the effort to learn every new thing that comes along. But here are our suggestions for languages and frameworks that we believe will stick around in the long run and are worth learning. They are all popular, have large communities, and give a lot of career opportunities.

1. JavaScript is everywhere

If you are doing web development, JavaScript is a language that you should know, regardless of what other language you write your backends in. These days you can use JS in the browser, on the server, in mobile apps and even on programmable hardware. ES6 will bring much needed improvements and will make the language even more powerful and easy to write. It is also a good idea to learn about Bower and npm, and also tools like jshint and jscs for code style and issue reporting.

2. AngularJS

angular

AngularJS is a JavaScript framework by Google, which quickly established itself as the enterprise way of building powerful web apps. With that recognition comes an increased demand for programmers experienced with the framework, and as a result, you will find it mentioned on the list of requirements of nearly every JavaScript-related job ad. But don’t jump into it just yet. It has been said that a large rewrite and rethinking of Angular is coming soon, so it would be better if you wait until version 2.0 is released before picking it up. See our guide with angularjs examples.

3. React

react

React is the newest entrant in this list, but it proved itself a practical realization of the idea for reusable web components. The library is developed by Facebook and provides very fast performance thanks to its virtual DOM, and can be easily plugged into existing projects. It also has a very active community that develops all kinds of components. In our opinion, React has a lot of potential and is the framework to watch (and learn) in 2015. See our quick react tutorial.

4. Node.js

nodejs

With Node.js you can develop networked server applications in JavaScript. It can be used for simple website backends using a framework like Express, API endpoints, websocket servers or even torrent clients. Node has an incredibly active community and surpassed every other language by module count this year. If you are a beginner, we recommend trying some of the interactive tutorials at NodeSchool.

5. NoSQL databases

nosql

Databases which need neither tables nor SQL are highly valued by today’s web developers and we believe these databases will only become more popular next year. The two noteworthy choices are Mongodb and Redis. It is much easier to get started with one of these databases than with MySQL and Postgres. But don’t get fooled into thinking that NoSQL databases are a perfect replacement – in some situations a classic relational database will make your development easier even if it takes more effort to set up.

6. Less/Sass/Stylus

lesscss

There is a lot to dislike about CSS. It is too easy to end up with an unwieldy 1000 line css file which is hard to navigate and change. To solve this, there are languages like Less, Sass and Stylus which are compiled to CSS and offer things like variables, macros and other goodies that will help you write better code. You can learn one of these in a single afternoon.

7. Exciting new frameworks

exciting-new-frameworks

Meteor is a radically new approach to web application development which blurs the boundaries between front end and back end. It allows you to write reall-time apps, and has a rapidly growing community writing packages for it. Hood.ie is a smaller contender, but offers a novel approach. It handles the backend for you, so you can concentrate entirely on the front end of your application.

8. Exciting new languages

exciting-new-languages

For the language nerds out there, here are some treats. Golang, Rust and Elixir are gaining momentum in programming circles and are used in situations which demand extremely high performance. We don’t recommend moving your development to one of these just yet, but you might want to do the interactive tutorials that are provided on their websites.

9. A classic full stack framework

full-stack-frameworks

Even though single page applications are gaining popularity, there is still a huge demand for classic server-side web apps. Ruby on Rails, Django, Laravel, Play, ASP.NET are the top full-stack frameworks at the moment. But any solid MVC framework will do wonders to your productivity if you take the time to study it.

10. The old guard

the-old-guard

There is a large collection of established languages and platforms that are still in demand – Java, .NET, Python, Ruby. They have large communities and will look good on any CV. They all have their pros and cons, but it doesn’t hurt to create small side projects in one of them every now and then. This is something that no programming course or tutorial will teach you and you will quickly get a feel whether that language fits with your way of work.

11. Don’t forget these

dont-forget-these

PHP, WordPress, and jQuery are still a perfectly valid way to create a website. WordPress has outgrown its blog platform past, and is now a powerful CMS/framework for developing a wide range of web applications. If you are a designer you should consider picking these technologies up. If you decide to go with PHP for your backend needs, don’t forget about the good practices in PHP the right way. Also, if you haven’t already, take a look at Bootstrap – it will help you write frontend code. There are also lots of bootstrap plugins you can choose from.

Source:: Tutorialzine.com

AngularJS Resources and Tutorials

Getting Started with AngularJS

  • https://egghead.io/- Awesome video tutorials, from beginner to pro
  • http://www.thinkster.io/ – How to build and deploy full single-page web applications using AngularJS
  • http://bitoftech.net/2014/01/13/tutorial-for-building-spa-using-angularjs-example/ – How to build SPA

Service? Factory? What?

  • http://iffycan.blogspot.com.br/2013/05/angular-service-or-factory.html

Best practices

  • https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub
  • https://www.youtube.com/watch?v=ZhfUv0spHCY — A must watch
  • http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls

 

AngularJS Resources 

  • http://ngmodules.org/ – A repository for third party AngularJS moduels
  • https://github.com/angular-ui/ – AngularUI – the most popular UI module for Angular
  • http://mgcrea.github.io/angular-strap/ – Twitter’s Bootstrap made for Angular!
  • https://github.com/jmcunningham/AngularJS-Learning – Huge resource of AngularJS links
  • http://code.tutsplus.com/tutorials/5-awesome-angularjs-features–net-25651

 

AngularJS Conceptual map

  • https://www.facebook.com/photo.php?fbid=623852151001889&set=gm.460351630731591&type=1

 

MEAN stack resources (Mongo, Express, Angular, and Node)

  • https://github.com/ericdouglas/MEAN-resources

 

Examples

  • http://todomvc.com/architecture-examples/angularjs/ – ToDo app example (really great site)

 

Blogs:

  • http://angular-tips.com/

$attrs.$observe vs $scope.$watch

  • http://stackoverflow.com/questions/14876112/difference-between-observers-and-watchers

== Lots of additional materials ==

  • http://yearofmoo-articles.github.io/angularjs-testing-article/app/#!/videos
  • http://angular-tips.com/blog/2013/08/why-does-angular-dot-js-rock/
  • http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html
  • http://net.tutsplus.com/tutorials/javascript-ajax/building-a-web-app-from-scratch-in-angularjs/
  • http://www.thinkster.io/pick/GtaQ0oMGIl/a-better-way-to-learn-angularjs

Scopes and $apply()

  • http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
  • https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply()
  • http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/
  • http://www.boynux.com/angularjs-apply-explained/

 

Sample Plunkers:

 

– How to integrate jQuery third party plugins with Angular

  • http://embed.plnkr.co/OYSNv5zjJ483XLWphc7g/preview

 

– Services + Controllers + ngMock

  • http://embed.plnkr.co/B5JTy5GU6ay2Cw5c7LAM/preview

 

A step-by-step on how scopes and dirty-checking works

  • http://teropa.info/blog/2013/11/20/writing-a-book-about-making-your-own-angularjs.html

 

Tips on how RESTful services should be made (backends/APIs)

  • http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful

 

When to use Controllers, Services or Directives

  • http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/
  • http://iffycan.blogspot.com.ar/2013/05/angular-service-or-factory.html

Using decorators

  • http://blog.codebrag.com/post/57412530001/preventing-duplicated-requests-in-angularjs
  • http://www.technofattie.com/2014/03/25/how-to-extend-angular-script-directive.html

Event Delegation

  • http://www.bennadel.com/blog/2448-Using-jQuery-Event-Delegation-In-AngularJS.htm

Directives (they are tough and awesome!)

  • http://thecodebarbarian.wordpress.com/2013/09/23/the-8020-guide-to-writing-angularjs-directives/
  • http://www.codinginsight.com/angularjs-directives/
  • http://www.benlesh.com/2012/11/angular-js-directive-basics.html
  • http://www.adobe.com/devnet/html5/articles/angularjs-directives-and-the-computer-science-of-javascript.html
  • http://www.bennadel.com/blog/2447-Exploring-Directive-Controllers-Compiling-Linking-And-Priority-In-AngularJS.htm
  • http://blog.berylliumwork.com/2013/04/facebook-login-with-javascript-sdk.html
  • http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/

Filters

  • http://thecodebarbarian.wordpress.com/2014/01/17/the-8020-guide-to-writing-and-using-angularjs-filters/

Unit testing

  • http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-testacular.html
  • http://andyshora.com/unit-testing-best-practices-angularjs.html

E2E testing

  • http://ramonvictor.github.io/protractor/slides/

Architecture

  • https://medium.com/@dickeyxxx/best-practices-for-building-angular-js-apps-266c1a4a6917
  • http://developer.telerik.com/featured/requiring-vs-browerifying-angular/
  • http://blog.artlogic.com/2013/05/02/ive-been-doing-it-wrong-part-1-of-3/
  • http://www.johnpapa.net/structuring-an-angular-project/
  • http://cliffmeyers.com/blog/2013/4/21/code-organization-angularjs-javascript
  • http://ify.io/lazy-loading-in-angularjs/
  • http://stackoverflow.com/questions/22537311/angular-ui-router-login-authentication

SEO tricks

  • http://www.yearofmoo.com/2012/11/angularjs-and-seo.html

Animations

  • http://www.yearofmoo.com/2013/04/animation-in-angularjs.html

i18n

  • http://thecodebarbarian.wordpress.com/2013/12/02/price-internationalization-with-the-mean-stack/
  • http://pascalprecht.github.io/slides/i18n-with-angular-translate/#/

Forms and validation

  • http://thecodebarbarian.wordpress.com/2013/05/12/how-to-easily-validate-any-form-ever-using-angularjs/
  • http://scotch.io/tutorials/javascript/angularjs-form-validation
  • http://www.chroder.com/2014/02/01/using-ngmodelcontroller-with-custom-directives/