Welcome!

Eclipse Authors: David H Deans, JP Morgenthal, Mano Marks, Liz McMillan, Yeshim Deniz

Related Topics: @CloudExpo, Java IoT, Containers Expo Blog, Eclipse

@CloudExpo: Blog Post

ES6 & Javascript in Harmony

An Overview of New Language Features

ES6 & Javascript in Harmony: An Overview of New Language Features

This article originally published on the Logentries blog.

ECMAScript 6 brings powerful new capabilities and some tasty syntactical sugar to the ubiquitous Javascript language, as it continues to grab an ever increasing slice of developer mindshare.

Now that the ES6 feature set is frozen and just minor refinements will be made over the coming months, much of this new functionality has already landed in modern browsers, and will continue to roll out with each new browser update.

For the impatient, there are also now several excellent precompile / polyfill / shim tools available, so you can start using these new features immediately; safely knowing that your code will run ‘natively' on every Javascript platform.

Javascript has become far more successful and ubiquitous than Brendan Eich or Netscape ever imagined, and several of the significant changes in the new spec, are designed with server side scripting platforms in mind (eg Node.js, and various scriptable database engines...).

This is an overview of some of the key changes in ES6

ES6 javascript new language features

Block Bindings

A new let keyword declares a variable (like var) but restricts its scope to the current code block (unlike var which is only scoped to function block); let also does not sharevar hoisting characteristics, so a let variable cannot be used until after its declaration (or it will throw an error).

function foo(){
  let x = 123;
  if(true){
    let x = 456;      
// different variable
    console.log(x);  
// 456
  }
  console.log(x);    
// 123
}

var i=0;
for(let i=i; i<10; i++){
  console.log(i);   
// 0 1 2 3 4 5 6 7 8 9
}
console.log(i)      
// 0

const is similar to let except once initialized, cannot be changed. const declarations share the same block scoping as let.

    const PI = 3.14159265359;
    let circumference = 2 * PI * r;

Arrow functions

Syntactical sugar (mostly) to facilitate simple function declaration, which is particularly handy for anonymous functions.

    // these are equivalent
    var sq = x => x * x
    var sq = function(x){ return x * x }

However, there are some important differences with standard function declarations:

  • The value of this inside an Arrow function is always determined by where it isdefinednot where it is used (avoiding common "var self = this" shuffle)
  • Arrow functions cannot change this within the function
  • Arrow functions cannot be used with new as constructors
  • Arrow functions have no arguments object, so must use standard named or new rest parameters
    var sum = (a,b) => a + b;
    var getName = () => "Pablo"; 
// empty parenthesis needed when no params
    var foo = (a,b) => { 
      let c = a + b; 
      console.log(a,b,c);        
// 1 2 3
    }

Because curly braces are used for the function's body, to return an object literal (outside of a function body) you must wrap the literal in parentheses.

var getObj = id => ({ id:id, name:"ObjA" });

Destructured assignment

Several variables can be initialized in a single statement and the following are equivalent:

    var [d, m, y] = [13, 2, 1963];
    var d = 13, m = 2, y = 1963;

    // useful for swapping
    [x, y] = [y, x]

    // or multiple return values
    function now(){ return [13, 2, 2013, 8, 0]; }
    var [d, m] = now(); // d = 13, m = 2
    var [,,y] = now(); // y = 2013

Destructuring also works with objects.

    function today() { return { d:13, m:2, y:1963 }; }
    var { m:month, y:year } = today(); 
// month = 2, year = 1963

// shorthand
    var { m, y } = today(); 
// m = 2, y = 1963

Destructuring assignments can also work with nested elements.

Parameters

There are several new conveniences for working with parameters.

Default Parameters

You can now assign default values to function parameters, which will be used if the parameter is not formally passed.

function myFunc( url, timeout=3000, callback=function(){} )

Rest Parameters

Designed to replace use of arguments when working with variable numbers of parameters, and indicated by three dots ... preceding a named parameter. The named parameter then becomes an array containing the rest of the parameters (passed but not specified).

    function sum(first, second, ...others){
      console.log(others.length);
    }

Spread Operator

Spread is the opposite of Rest parameters and splits an array into individual parameters.

    var a = [1,2,3,4,5]
    max = Math.max(...a) 
// equivalent to Math.max.apply(null,a) 
// or Math.max(1,2,3,4,5)

Spread can also be used in conjunction with other regular parameters.

Destructured Parameters

Similar to a destructured assignment (see above).

function setCookie( name, val, { secure, path, domain, expires })

Iterators and Generators

Iterators are objects that have a next() method which returns a results object with two properties, value and done. Iterators offer a collection of values one at a time through successive calls to next() returning the appropriate value or result with done==true if no more values to read.

ES6 collection objects (like arrays, maps and sets) all have three default iterators. These are entries()values() and keys() and cover most common iteration needs.

    var a=['one','two','three']
    for(let e of a.entries()) console.log(e)  
// [0,'one']  [1,'two']  [2,'three']
    for(let v of a.values()) console.log(v)   
// one  two  three
    for(let k of a.keys()) console.log(k)     
// 0  1  2

for..of

ES6 also introduces a new syntax for dealing with iterators. The for-of loop which is used for looping over iterable objects.

for(let i of ['one','two','three') console.log(i)

NOTE: for..of and for..in loops look similar, but are fundamentally different.for..in is for inspecting object properties and looping over the object's enumerable properties, whereas for..of is for looping over iterators.

for..of is also available in array comprehensions.

    [ x for (x of a) if (x>5) ]

Generators

A generator is a special kind of function that returns an iterator by inserting a * after thefunction keyword. A new yield keyword is used inside of generators to specify values that iterator should return when next() is called.

Generators stop execution after each yield until next() is called again, which is a powerful new paradigm (eg for managing asynchronous processes).

    function* gen(){
      yield 1;
      yield 2;
      yield 3;
    }
    let it = gen();
    for(let i of it) console.log(i); 
// outputs 1 2 3

    let it2 = gen();
    it2.next() // { value:0, done:false }
    it2.next() // { value:1, done:false }
    it2.next() // { value:2, done:false }
    it2.next() // { value:undefined, done:true }

Generators also let us write lazy versions of many functions (eg. filter, map, reduce...) which are very efficient and elegant.

Collections

ES6 introduces some new collection structures.

Sets

Sets are simple data structures similar to arrays where each value is unique.

    let s = new Set([1,2,3]);
    s.has(4);     // false
    s.add(4);     // [1,2,3,4]
    s.add(2);     // still [1,2,3,4]
    s.delete(3);  // [1,2,4]

Maps

Maps are similar to JavaScript object key-value pairs except the key can be any JavaScript data type, not just strings.

    m = new Map();
    o = {x:'blah'};
    m.set(o,'something to store');
    m.has(o); // true
    console.log(m.get(o));

Maps can also be used with iterators.

    for (let [k, v] of m) console.log(k, v);

Symbols

Symbols generate unique inaccessible keys, useful in maps and class private members.

    let a = Map();
    {
      let k = Symbol();
      a.set(k, 'value');
// Here, we can get and reset 'value' as a.get(k).
    }
// Here, a.get(k) is invalid, a.size is 1, 
// but the key cannot be seen.

WeakMaps and WeakSets

WeakMap helps developers avoid memory leaks by allowing the garbage collector to dispose objects only referenced by WeakMap. WeakMap keys must be objects and are not able to enumerate their keys.

WeakSet only objects, which can be collected if there are no other references or mentions.

Template Strings

New String declaration syntax (using back-ticks ") that facilitates simple String literals with embedded expression evaluation.

    var name = 'Paul', age = 99;
    var s = `$(name), is apparently $(age) years old`

The syntax can also be used fro simple multi-line strings.

    var longString = `here we have
     a multiline string 
     using backtick quotes`;

Promises

Promises are a mechanism for handling results (and errors) from asynchronous operations. You can achieve the same thing with callbacks, but promises provide improved readability via method chaining and simple error handling. Promises are already used in many JavaScript libraries.

    getJSON("/api/product/1").then( function(p) {
      return getJSON(p.description);
    }).catch(function(err) {
      console.log('Oops..',err)
    });

 

More Stories By Trevor Parsons

Trevor Parsons is Chief Scientist and Co-founder of Logentries. Trevor has over 10 years experience in enterprise software and, in particular, has specialized in developing enterprise monitoring and performance tools for distributed systems. He is also a research fellow at the Performance Engineering Lab Research Group and was formerly a Scientist at the IBM Center for Advanced Studies. Trevor holds a PhD from University College Dublin, Ireland.

@ThingsExpo Stories
SYS-CON Events announced today that HTBase will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. HTBase (Gartner 2016 Cool Vendor) delivers a Composable IT infrastructure solution architected for agility and increased efficiency. It turns compute, storage, and fabric into fluid pools of resources that are easily composed and re-composed to meet each application’s needs. With HTBase, companies can quickly prov...
There are 66 million network cameras capturing terabytes of data. How did factories in Japan improve physical security at the facilities and improve employee productivity? Edge Computing reduces possible kilobytes of data collected per second to only a few kilobytes of data transmitted to the public cloud every day. Data is aggregated and analyzed close to sensors so only intelligent results need to be transmitted to the cloud. Non-essential data is recycled to optimize storage.
"I think that everyone recognizes that for IoT to really realize its full potential and value that it is about creating ecosystems and marketplaces and that no single vendor is able to support what is required," explained Esmeralda Swartz, VP, Marketing Enterprise and Cloud at Ericsson, in this SYS-CON.tv interview at @ThingsExpo, held June 7-9, 2016, at the Javits Center in New York City, NY.
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that IoT Now has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex softw...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, will discuss the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information,
As businesses adopt functionalities in cloud computing, it’s imperative that IT operations consistently ensure cloud systems work correctly – all of the time, and to their best capabilities. In his session at @BigDataExpo, Bernd Harzog, CEO and founder of OpsDataStore, will present an industry answer to the common question, “Are you running IT operations as efficiently and as cost effectively as you need to?” He will expound on the industry issues he frequently came up against as an analyst, and...
Keeping pace with advancements in software delivery processes and tooling is taxing even for the most proficient organizations. Point tools, platforms, open source and the increasing adoption of private and public cloud services requires strong engineering rigor - all in the face of developer demands to use the tools of choice. As Agile has settled in as a mainstream practice, now DevOps has emerged as the next wave to improve software delivery speed and output. To make DevOps work, organization...
Apache Hadoop is emerging as a distributed platform for handling large and fast incoming streams of data. Predictive maintenance, supply chain optimization, and Internet-of-Things analysis are examples where Hadoop provides the scalable storage, processing, and analytics platform to gain meaningful insights from granular data that is typically only valuable from a large-scale, aggregate view. One architecture useful for capturing and analyzing streaming data is the Lambda Architecture, represent...
My team embarked on building a data lake for our sales and marketing data to better understand customer journeys. This required building a hybrid data pipeline to connect our cloud CRM with the new Hadoop Data Lake. One challenge is that IT was not in a position to provide support until we proved value and marketing did not have the experience, so we embarked on the journey ourselves within the product marketing team for our line of business within Progress. In his session at @BigDataExpo, Sum...
Things are changing so quickly in IoT that it would take a wizard to predict which ecosystem will gain the most traction. In order for IoT to reach its potential, smart devices must be able to work together. Today, there are a slew of interoperability standards being promoted by big names to make this happen: HomeKit, Brillo and Alljoyn. In his session at @ThingsExpo, Adam Justice, vice president and general manager of Grid Connect, will review what happens when smart devices don’t work togethe...
SYS-CON Events announced today that Ocean9will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Ocean9 provides cloud services for Backup, Disaster Recovery (DRaaS) and instant Innovation, and redefines enterprise infrastructure with its cloud native subscription offerings for mission critical SAP workloads.
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), will provide an overview of various initiatives to certifiy the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldw...
SYS-CON Events announced today that Technologic Systems Inc., an embedded systems solutions company, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Technologic Systems is an embedded systems company with headquarters in Fountain Hills, Arizona. They have been in business for 32 years, helping more than 8,000 OEM customers and building over a hundred COTS products that have never been discontinued. Technologic Systems’ pr...
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From ...
The taxi industry never saw Uber coming. Startups are a threat to incumbents like never before, and a major enabler for startups is that they are instantly “cloud ready.” If innovation moves at the pace of IT, then your company is in trouble. Why? Because your data center will not keep up with frenetic pace AWS, Microsoft and Google are rolling out new capabilities In his session at 20th Cloud Expo, Don Browning, VP of Cloud Architecture at Turner, will posit that disruption is inevitable for c...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...