Welcome!

Machine Learning Authors: William Schmarzo, Kevin Jackson, Stackify Blog, Elizabeth White, Pat Romanski

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.

@CloudExpo Stories
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"ZeroStack is a startup in Silicon Valley. We're solving a very interesting problem around bringing public cloud convenience with private cloud control for enterprises and mid-size companies," explained Kamesh Pemmaraju, VP of Product Management at ZeroStack, 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.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Infoblox does DNS, DHCP and IP address management for not only enterprise networks but cloud networks as well. Customers are looking for a single platform that can extend not only in their private enterprise environment but private cloud, public cloud, tracking all the IP space and everything that is going on in that environment," explained Steve Salo, Principal Systems Engineer at Infoblox, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventio...
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, 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.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, discussed how by using ne...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, 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.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
Vulnerability management is vital for large companies that need to secure containers across thousands of hosts, but many struggle to understand how exposed they are when they discover a new high security vulnerability. In his session at 21st Cloud Expo, John Morello, CTO of Twistlock, addressed this pressing concern by introducing the concept of the “Vulnerability Risk Tree API,” which brings all the data together in a simple REST endpoint, allowing companies to easily grasp the severity of the ...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, discussed how data centers of the future will be managed, how the p...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, 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.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, 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.