Welcome!

Eclipse Authors: Pat Romanski, Elizabeth White, Liz McMillan, David H Deans, JP Morgenthal

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 Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning 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 busin...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...