ECMAScript 6 new features compare ECMAScript 5

This is to compare the difference between ECMAScript 6 and ECMAScript 5

Use ECMAScript 6 you could reduced lots code , but the core problem is not all the browser support, to resolve this ECMAScript 6 need to use a compiler to transform your ECMAScript 6 code to ECMAScript 5 compatible code, in this purpose you could use Babel which allowed you run in current browsers

As follow is introduced some syntax that I used often in ES5 and it’s completely shorten in ES6

Before you should know the difference between var, let and const

compare to var, let will be more strict but it also changeable in the block scope,

const in the word means it is immutable, try in browser to defined between then you could find the error notice once you had declared with let and const, this could be more easy to debug since it’s more strict compare var

you could get more introduction here

1 Constants

ES5

//  only in ES5 through the help of object properties
//  and only in global context and not in a block scope
Object.defineProperty(typeof global === "object" ? global : window, "PI", {
    value:        3.141593,
    enumerable:   true,
    writable:     false,
    configurable: false
})
PI > 3.0;

ES6

const PI = 3.141593
PI > 3.0

In ES6 you could defined the constant, variables which cannot be re-assigned new content, but in case the content is an object, this means the object itself can still be altered: ( follow as resign value and it show error, but property in object can be added or removed or be changed) :

2  Scoping: Block-scoped Variables

without hoisting, so you do not need to declare variable to the top of the current script or the current function

ES5

var i, x, y;
for (i = 0; i < a.length; i++) {
    x = a[i];
    …
}
for (i = 0; i < b.length; i++) {
    y = b[i];
    …
}

var callbacks = [];
for (var i = 0; i <= 2; i++) {
    (function (i) {
        callbacks[i] = function() { return i * 2; };
    })(i);
}
callbacks[0]() === 0;
callbacks[1]() === 2;
callbacks[2]() === 4;

ES6

for (let i = 0; i < a.length; i++) {
    let x = a[i]
    …
}
for (let i = 0; i < b.length; i++) {
    let y = b[i]
    …
}

let callbacks = []
for (let i = 0; i <= 2; i++) {
    callbacks[i] = function () { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4

3 Arrow Functions, which reduced funtion expressive closure syntax

ES5

odds  = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums  = evens.map(function (v, i) { return v + i; });

ES6

odds  = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums  = evens.map((v, i) => v + i)

and so does statement bodies:
ES5

nums.forEach(function (v) {
   if (v % 5 === 0)
       fives.push(v);
});

ES6

nums.forEach(v => {
   if (v % 5 === 0)
       fives.push(v)
})

Lexical this

ES5

//  variant 1
var self = this;
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        self.fives.push(v);
});

//  variant 2
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}, this);

//  variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}.bind(this));

ES6

this.nums.forEach((v) => {
    if (v % 5 === 0)
        this.fives.push(v)
})

3 Extended Parameter Handling
ES6 could be like other functional programme lauguage, you could simple and intuitive default values in your function parameters:

ES5

function f (x, y, z) {
    if (y === undefined)
        y = 7;
    if (z === undefined)
        z = 42;
    return x + y + z;
};
f(1) === 50;

ES6

function f (x, y = 7, z = 42) {
    return x + y + z
}
f(1) === 50

And you could use aggregation of remaining arguments into single parameter of variadic functions, aggregation is quiet useful in Reactjs

ES5

function f (x, y) {
    var a = Array.prototype.slice.call(arguments, 2);
    return (x + y) * a.length;
};
f(1, 2, "hello", true, 7) === 9;

ES6

function f (x, y, ...a) {
    return (x + y) * a.length
}
f(1, 2, "hello", true, 7) === 9

Spreading of elements in an array or a string into both literal elements:

ES5

var params = [ "hello", true, 7 ];
var other = [ 1, 2 ].concat(params); // [ 1, 2, "hello", true, 7 ]

ES6

var params = [ "hello", true, 7 ]
var other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ]

Template Literals
String Interpolation for output of defined variables, this is quiet useful once you had lots string to express, for example show error message string in JS:
instead of using “+ card.amount +” , used ${card.amount} is more readable
ES5

var customer = { name: "Foo" };
var card = { amount: 7, product: "Bar", unitprice: 42 };
var message = "Hello " + customer.name + ",\n" +
"want to buy " + card.amount + " " + card.product + " for\n" +
"a total of " + (card.amount * card.unitprice) + " bucks?";

ES6

var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`

Enhanced Object Properties

Property Shorthand:

ES5

var x = 0, y = 0;
obj = { x: x, y: y };

ES6

var x = 0, y = 0
obj = { x, y }

Computed Property Names

ES5

var obj = {
    foo: "bar"
};
obj[ "baz" + quux() ] = 42;

ES6

let obj = {
    foo: "bar",
    [ "baz" + quux() ]: 42
}

Class definition
like other OOP functional language, ES6 could be more intuitive, OOP-style and boilerplate-free classes, if you write php then you will love this point

ES5

var Shape = function (id, x, y) {
    this.id = id;
    this.move(x, y);
};
Shape.prototype.move = function (x, y) {
    this.x = x;
    this.y = y;
};

ES6

class Shape {
    constructor (id, x, y) {
        this.id = id
        this.move(x, y)
    }
    move (x, y) {
        this.x = x
        this.y = y
    }
}

New Built-In Methods

Object Property Assignment: assign()

this will return the value of assign target object
ES5

var dest = { quux: 0 };
var src1 = { foo: 1, bar: 2 };
var src2 = { foo: 3, baz: 4 };
Object.keys(src1).forEach(function(k) {
    dest[k] = src1[k];
});
Object.keys(src2).forEach(function(k) {
    dest[k] = src2[k];
});
dest.quux === 0;
dest.foo  === 3;
dest.bar  === 2;
dest.baz  === 4;

ES6

var dest = { quux: 0 }
var src1 = { foo: 1, bar: 2 }
var src2 = { foo: 3, baz: 4 }
Object.assign(dest, src1, src2)
dest.quux === 0
dest.foo  === 3
dest.bar  === 2
dest.baz  === 4

Array Element Finding
New function for finding an element in an array

ES5

[ 1, 3, 4, 2 ].filter(function (x) { return x > 3; })[0]; // 4
// no equivalent in ES5

ES6

[ 1, 3, 4, 2 ].find(x => x > 3) // 4
[ 1, 3, 4, 2 ].findIndex(x => x > 3) // 2

String Repeating

ES5

Array((4 * depth) + 1).join(" ");
Array(3 + 1).join("foo");

ES6

" ".repeat(4 * depth)
"foo".repeat(3)

String Searching
New specific string functions to search for a sub-string

ES5

"hello".startsWith("ello", 1) // true
"hello".endsWith("hell", 4)   // true
"hello".includes("ell")       // true
"hello".includes("ell", 1)    // true
"hello".includes("ell", 2)    // false

ES6

"hello".indexOf("ello") === 1;    // true
"hello".indexOf("hell") === (4 - "hell".length); // true
"hello".indexOf("ell") !== -1;    // true
"hello".indexOf("ell", 1) !== -1; // true
"hello".indexOf("ell", 2) !== -1; // false

Number Truncation
Truncate a floating point number to its integral part, completely dropping the fractional part.
ES5

function mathTrunc (x) {
    return (x < 0 ? Math.ceil(x) : Math.floor(x));
}
console.log(mathTrunc(42.7)) // 42
console.log(mathTrunc( 0.1)) // 0
console.log(mathTrunc(-0.1)) // -0

ES6

console.log(Math.trunc(42.7)) // 42
console.log(Math.trunc( 0.1)) // 0
console.log(Math.trunc(-0.1)) // -0

lazy load js

what is lazy load, the basic concept is spped up page loading time especially it’s comes to lots images

There’s some library to use for, like echo.js
or beLazy.js

Here we introduced lazy-load-xt

Why?

Simply it does support: css animation like transitions affect, it is support scrollable containers like IFRAME contend, and more other media like videos, and even no script support ( disable js support)

well, it is just more powerful, but if you simply just want load images faster you could consider just use upper introduced library

But remember it is has to user jQuery 1.7

How to use?

1 Installation:

You could install by node js or bower

$ npm install lazyloadxt
$ bower install lazyloadxt

or simply use this cdn

2 add html tag to called the image src, or you could defined a variable to call image src

data-src

3 Then defined image size or any css style for layout

4 That’s it you should be able see the image load

and here has so API to play with

$.extend($.lazyLoadXT, {
  edgeY:  200,
  srcAttr: 'data-src'
});

output:

 

code play here

ResfulAPI, what’s all about?

downloadWhat is ResfulAPI?


Actually it does get bit time for me to understand what is restful API, I mean I though I do understand it, since use post, get, update, delete action, but actually not at all. It’s not only about the action, it’s also about the whole react concept design pattern after those action. Haha, still not get it right? me too!!

Well, that’s better describe like this:

roles:

1.”Browser” == “client”,

2.”Server” == “shop”,

action:

Client ask shop : ” please give me Black chocolate”,

shop receive from Client: “ok, got your message, I will send you Black chocolate”

result:

shop send client Black chocolate

You could see through this scenario, there’s has roles, verb(ask, receive), result

those all play drama called ” Restful API”

Got it a bit more? in big view, Restful API is Representation State Transfer, it’s about the architectural style, there’s no standard of how you build your restful API ( like if you write your drama there should be no standard pattern, right?), it’s all about the action between Browser | Server, and how you communicate with for the object you want get.

Here is sample graphic from above drama:

CrunchifyGot more clarify? So RestfulAPI is this drama whole picture gathers by: Browser| Web Server, action by method: GET, POST, PUT, DELET etc, and Browser will react the result to the web page.

When I finally get this concept, then you will see the key point is to communicate between Browser | Web Server, so what is this tool? Mostly we use http this media to connect both. So we got to finger out what is http request

 

What is http request?


This is like how to design method of communication, we could send the specific request and get the specific product we want directly or we could send the the common request and retrieve one of the product in the whole list. Depend on your request and also depend on how complexity of list products. Well, like the way we want range book category in our bookshelf

But in terms we could look at this way:

Nouns: like whole collects of our books, our resource, in http, we said this is like URL, for example

http: //book.com/books/{list}

Verbs: this is the way we act to book from our bookshelf, you could get the book, remove the book, in http, we use GET, POST, PUT,DELET.

Content types: The book info like book author name, editor, publish date. in http, we show this information with XML, JSON, YAML format.

Here is the graphic to show the whole concept:

RESTful-Triangle

So if I want book 1 , the URL could be like this to get book 1: http: //book.com/books/1,

If I want the author info, publish date from book 1, the URL could be like this: http: //book.com/books/1?authorInfo=John&publishDate=2016

Here we could get authorInfo : “John”, and publish date: “2016”

in JSON format will be looks like this:

{

“book”:[{

“authorInfo” : “John”,

“publishDate”: “2016”

}]

}

In this URL, we could use action by GET or POST to get those information. And different between GET & POST? you could look at here.

And action should be return back status, right?

So http has status code to show return status:

200: ok,

404: Not Found,

500: internal Server Error

Here’s link you could look all the different status

 

How do you look those API through web browser?


Open web browser, F12, you could click Network and see the api run through web event binding:

CaptureFor example here, the resource(nouns) is :https://stripe-s.pointroll.com/api/data/get/376?model=touareg&zip=55344

method is get

content type resource is: 376?model=touareg&zip=55344, which is json format:

CaptureAnd how will this information show in our final destination: web browser?

You could use any language, here I use javascript:

  1. first load this resource
  2. second define the condition, if process 1 is success, we need to get offers list deal, and get title: “499/month for 36 months.”
  3. if process 1 is not success, then web browser show show status
  4. And final show the result in web site

The concept code will be like this:

$('#main-menu a').click(function(event) {
   event.preventDefault();
   
   $.ajax(this.href, {
      success: function(data) {
         $('#main').text(data.offers.deal.title);
      },
      error: function() {
         $('#notification-bar').text('An error occurred');
         //console.log("fn xhr.status: " + xhr.status);
      }
   });
});

So the final expectation is show the title: 499/month for 36 months on the browser web page.

Conclusion


This is just basic concept, it has also lots method to use, Rest data elements, connectors, components. This could be description in whole book, but I think the basic Restful API concept is keep simple, cause original ideal is reduce communication work between front & backend. So if not keep it simple, then what does make sense to use it?

But it does true, keep it simple could be the most difficult part!! I am new in this too, so any error or lack of sense part please feedback as much as you could. thank you!!