Welcome!

Eclipse Authors: Liz McMillan, David H Deans, JP Morgenthal, Mano Marks, 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
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software in the hope of capturing value in IoT. Although IoT is relatively new in the market, it has already gone through many promotional terms such as IoE, IoX, SDX, Edge/Fog, Mist Compute, etc. Ultimately, irrespective of the name, it is about deriving value from independent software assets participating in an ecosystem as one comprehensive solution.
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, 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. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
SYS-CON Events announced today that T-Mobile 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. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
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.
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.
The 20th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held June 6-8, 2017, at the Javits Center in New York City, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal ...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, 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. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
With billions of sensors deployed worldwide, the amount of machine-generated data will soon exceed what our networks can handle. But consumers and businesses will expect seamless experiences and real-time responsiveness. What does this mean for IoT devices and the infrastructure that supports them? More of the data will need to be handled at - or closer to - the devices themselves.
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, 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. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Analytic. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.