What’s New in ES2018

In this article, I’ll cover the new features of JavaScript introduced via ES2018 (ES9), with examples of what they’re for and how to use them.
JavaScript (ECMAScript) is an ever-evolving standard implemented by many vendors across multiple platforms. ES6 (ECMAScript 2015) was a large release which took six years to finalize. A new annual release process has been formulated to streamline the process and add features quicker. ES9 (ES2018) is the latest iteration at the time of writing.
Technical Committee 39 (TC39) consists of parties including browser vendors who meet to push JavaScript proposals along a strict progression path:
Stage 0: strawman –
The initial submission of ideas.
Stage 1: proposal –
A formal proposal document championed by at least once member of TC39 which includes API examples.
Stage 2: draft –
An initial version of the feature specification with two experimental implementations.
Stage 3: candidate –
The proposal specification is reviewed and feedback is gathered from vendors.
Stage 4: finished –
The proposal is ready for inclusion in ECMAScript but may take longer to ship in browsers and Node.js.
ES2016
ES2016 proved the standardization process by adding just two small features:

The array includes() method, which returns true or false when a value is contained in an array, and
The a ** b exponentiation operator, which is identical to Math.pow(a, b).

ES2017
ES2017 provided a larger range of new features:

Async functions for a clearer Promise syntax
Object.values() to extract an array of values from an object containing name–value pairs
Object.entries(), which returns an array of sub-arrays containing the names and values in an object
Object.getOwnPropertyDescriptors() to return an object defining property descriptors for own properties of another object (.value, .writable, .get, .set, .configurable, .enumerable)
padStart() and padEnd(), both elements of string padding
trailing commas on object definitions, array declarations and function parameter lists
SharedArrayBuffer and Atomics for reading from and writing to shared memory locations (disabled in response to the Spectre vulnerability).

Refer to What’s New in ES2017 for more information.
ES2018
ECMAScript 2018 (or ES9 if you prefer the old notation) is now available. The following features have reached stage 4, although working implementations will be patchy across browsers and runtimes at the time of writing.
Asynchronous Iteration
At some point in your async/await journey, you’ll attempt to call an asynchronous function inside a synchronous loop. For example:
async function process(array) {
for (let i of array) {
await doSomething(i);
}
}

It won’t work. Neither will this:
async function process(array) {
array.forEach(async i => {
await doSomething(i);
});
}

The loops themselves remain synchronous and will always complete before their inner asynchronous operations.
ES2018 introduces asynchronous iterators, which are just like regular iterators except the next() method returns a Promise. Therefore, the await keyword can be used with for … of loops to run asynchronous operations in series. For example:
async function process(array) {
for await (let i of array) {
doSomething(i);
}
}

The post What’s New in ES2018 appeared first on SitePoint.

Link: https://www.sitepoint.com/es2018-whats-new/

Interactive Data Visualization with Modern JavaScript and D3

In this article, I want to take you through an example project that I built recently — a totally original type of visualization using the D3 library, which showcases how each of these components add up to make D3 a great library to learn.
D3 stands for Data Driven Documents. It’s a JavaScript library that can be used to make all sorts of wonderful data visualizations and charts.
If you’ve ever seen any of the fabulous interactive stories from the New York Times, you’ll already have seen D3 in action. You can also see some cool examples of great projects that have been built with D3 here.
The learning curve is pretty steep for getting started with the library, since D3 has a few special quirks that you probably won’t have seen before. However, if you can get past the first phase of learning enough D3 to be dangerous, then you’ll soon be able to build some really cool stuff for yourself.
There are three main factors that really make D3 stand out from any other libraries out there:

Flexibility. D3 lets you take any kind of data, and directly associate it with shapes in the browser window. This data can be absolutely anything, allowing for a huge array of interesting use cases to create completely original visualizations.
Elegance. It’s easy to add interactive elements with smooth transitions between updates. The library is written beautifully, and once you get the hang of the syntax, it’s easy to keep your code clean and tidy.
Community. There’s a vast ecosystem of fantastic developers using D3 already, who readily share their code online. You can use sites like bl.ocks.org and blockbuilder.org to quickly find pre-written code by others, and copy these snippets directly into your own projects.

The Project
As an economics major in college, I had always been interested in income inequality. I took a few classes on the subject, and it struck me as something that wasn’t fully understood to the degree that it should be.
I started exploring income inequality using Google’s Public Data Explorer …

When you adjust for inflation, household income has stayed pretty much constant for the bottom 40% of society, although per-worker productivity has been skyrocketing. It’s only really been the top 20% that have reaped more of the benefits (and within that bracket, the difference is even more shocking if you look at the top 5%).
Here was a message that I wanted to get across in a convincing way, which provided a perfect opportunity to use some D3.js, so I started sketching up a few ideas.
Sketching
Because we’re working with D3, I could more or less just start sketching out absolutely anything that I could think of. Making a simple line graph, bar chart, or bubble chart would have been easy enough, but I wanted to make something different.
I find that the most common analogy that people tended to use as a counterargument to concerns about inequality is that “if the pie gets bigger, then there’s more to go around”. The intuition is that, if the total share of GDP manages to increase by a large extent, then even if some people are getting a thinner slice of pie, then they’ll still be better off. However, as we can see, it’s totally possible for the pie to get bigger and for people to be getting less of it overall.
My first idea for visualizing this data looked something like this:

The idea would be that we’d have this pulsating pie chart, with each slice representing a fifth of the US income distribution. The area of each pie slice would relate to how much income that segment of the population is taking in, and the total area of the chart would represent its total GDP.
However, I soon came across a bit of a problem. It turns out that the human brain is exceptionally poor at distinguishing between the size of different areas. When I mapped this out more concretely, the message wasn’t anywhere near as obvious as it should have been:

Here, it actually looks like the poorest Americans are getting richer over time, which confirms what seems to be intuitively true. I thought about this problem some more, and my solution involved keeping the angle of each arc constant, with the radius of each arc changing dynamically.

Here’s how this ended up looking in practice:

I want to point out that this image still tends to understate the effect here. The effect would have been more obvious if we used a simple bar chart:

However, I was committed to making a unique visualization, and I wanted to hammer home this message that the pie can get bigger, whilst a share of it can get smaller. Now that I had my idea, it was time to build it with D3.
Borrowing Code
So, now that I know what I’m going to build, it’s time to get into the real meat of this project, and start writing some code.
You might think that I’d start by writing my first few lines of code from scratch, but you’d be wrong. This is D3, and since we’re working with D3, we can always find some pre-written code from the community to start us off.
We’re creating something completely new, but it has a lot in common with a regular pie chart, so I took a quick look on bl.ocks.org, and I decided to go with this classic implementation by Mike Bostock, one of the creators of D3. This file has probably been copied thousands of times already, and the guy who wrote it is a real wizard with JavaScript, so we can be sure that we’re starting with a nice block of code already.
This file is written in D3 V3, which is now two versions out of date, since version 5 was finally released last month. A big change in D3 V4 was that the library switched to using a flat namespace, so that scale functions like d3.scale.ordinal() are written like d3.scaleOrdinal() instead. In version 5, the biggest change was that data loading functions are now structured as Promises, which makes it easier to handle multiple datasets at once.
To avoid confusion, I’ve already gone through the trouble of creating an updated V5 version of this code, which I’ve saved on blockbuilder.org. I’ve also converted the syntax to fit with ES6 conventions, such as switching ES5 anonymous functions to arrow functions.
Here’s what we’re starting off with already:

I then copied these files into my working directory, and made sure that I could replicate everything on my own machine. If you want to follow along with this tutorial yourself, then you can clone this project from our GitHub repo. You can start with the code in the file starter.html. Please note that you will need a server (such as this one) to run this code, as under the hood it relies on the Fetch API to retrieve the data.
Let me give you a quick rundown of how this code is working.
The post Interactive Data Visualization with Modern JavaScript and D3 appeared first on SitePoint.

Link: https://www.sitepoint.com/interactive-data-visualization-javascript-d3/

Use Parcel to Bundle a Hyperapp App & Deploy to GitHub Pages

In a previous post we met Hyperapp, a tiny library that can be used to build dynamic, single-page web apps in a similar way to React or Vue.
In this post we’re going to turn things up a notch. We’re going to create the app locally (we were working on CodePen previously), learn how to bundle it using Parcel (a module bundler similar to webpack or Rollup) and deploy it to the web using GitHub Pages.
Don’t worry if you didn’t complete the project from the first post. All the code is provided here (although I won’t go into detail explaining what it does) and the principles outlined can be applied to most other JavaScript projects.
If you’d like to see what we’ll be ending up with, you can view the finished project here, or download the code from our GitHub repo.
Basic Setup
In order to follow along, you’ll need to have both Node.js and npm installed (they come packaged together). I’d recommend using a version manager such as nvm to manage your Node installation (here’s how), and if you’d like some help getting to grips with npm, then check out our beginner-friendly npm tutorial.
We’ll be using the terminal commands to create files and folders, but feel free to do it by just pointing and clicking instead if that’s your thing.
To get started, create a new folder called hyperlist:
mkdir hyperlist

Now change to that directory and initialize a new project using npm:
cd hyperlist/
npm init

This will prompt you to answer some questions about the app. It’s fine to just press enter to accept the default for any of these, but feel free to add in your name as the author and to add a description of the app.
This should create a file called package.json inside the hyperlist directory that looks similar to the following:
{
“name": "hyperlist",
"version": "1.0.0",
"description": "A To-do List made with Hyperapp",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "DAZ",
"license": "MIT"
}

Now we need to install the Hyperapp library. This is done using npm along with the –save flag, which means that the package.json file will be updated to include it as a dependency:
npm install –save hyperapp

This might give some warnings about not having a repository field. Don’t worry about this, as we’ll be fixing it later. It should update the package.json file to include the following entry (there might be a slight difference in version number):
"dependencies": {
"hyperapp": "^1.2.5"
}

It will also create a directory called node_modules where all the Hyperapp files are stored, as well as a file called package-lock.json. This is used to keep track of the dependency tree for all the packages that have been installed using npm.
Now we’re ready to start creating the app!
Folder Structure
It’s a common convention to put all of your source code into a folder called src. Within this folder, we’re going to put all of our JavaScript files into a directory called js. Let’s create both of those now:
mkdir -p src/js

In the previous post we learned that apps are built in Hyperapp using three main parts: state, actions and view. In the interests of code organization, we’re going to place the code for each part in a separate file, so we need to create these files inside the js directory:
cd src/js
touch state.js actions.js view.js

Don’t worry that they’re all empty. We’ll add the code soon!
Last of all, we’ll go back into the src directory and create our “entry point” files. These are the files that will link to all the others. The first is index.html, which will contain some basic HTML, and the other is index.js, which will link to all our other JavaScript files and also our SCSS files:
cd ..
touch index.html index.js

Now that our folder structure is all in place, we can go ahead and start adding some code and wiring all the files together. Onward!
Some Basic HTML
We’ll start by adding some basic HTML code to the index.html file. Hyperapp takes care of creating the HTML and can render it directly into the tag. This means that we only have to set up the meta information contained in the <head> tag. Except for the <title> tag’s value, you can get away with using the same index.html file for every project. Open up index.html in your favorite text editor and add the following code:
<!doctype html>
<html lang=’en’>
<head>
<meta charset=’utf-8’>
<meta name=’viewport’ content=’width=device-width, initial-scale=1’>
<title>HyperList</title>
</head>
<body>
<script src=’index.js’></script>
</body>
</html>

Now it’s time to add some JavaScript code!
ES6 Modules
Native JavaScript modules were introduced in ES6 (aka ES2015). Unfortunately, browsers have been slow to adopt the use of ES6 modules natively, although things are now starting to improve. Luckily, we can still use them to organize our code, and Parcel will sort out piecing them all together.
Let’s start by adding the code for the initial state inside the state.js file:
const state = {
items: [],
input: ”,
placeholder: ‘Make a list..’
};

export default state;

This is the same as the object we used in the previous article, but with the export declaration at the end. This will make the object available to any other file that imports it. By making it the default export, we don’t have to explicitly name it when we import it later.
Next we’ll add the actions to actions.js:
const actions = {
add: () => state => ({
input: ”,
items: state.items.concat({
value: state.input,
completed: false,
id: Date.now()
})
}),
input: ({ value }) => ({ input: value }),
toggle: id => state => ({
items: state.items.map(item => (
id === item.id ? Object.assign({}, item, { completed: !item.completed }) : item
))
}),
destroy: id => state => ({
items: state.items.filter(item => item.id !== id)
}),
clearAllCompleted: ({ items }) => ({
items: items.filter(item => !item.completed)
})
};

export default actions;

Again, this is the same as the object we used in the previous article, with the addition of the export declaration at the end.
Last of all we’ll add the view code to view.js:
import { h } from ‘hyperapp’

const AddItem = ({ add, input, value, placeholder }) => (
<div class=’flex’>
<input
type="text"
onkeyup={e => (e.keyCode === 13 ? add() : null)}
oninput={e => input({ value: e.target.value })}
value={value}
placeholder={placeholder}
/>
<button onclick={add}>+</button>
</div>
);

const ListItem = ({ value, id, completed, toggle, destroy }) => (
<li class={completed && "completed"} id={id} key={id} onclick={e => toggle(id)}>
{value} <button onclick={ () => destroy(id) }>x</button>
</li>
);

const view = (state, actions) => (
<div>
<h1><strong>Hyper</strong>List</h1>
<AddItem
add={actions.add}
input={actions.input}
value={state.input}
placeholder={state.placeholder}
/>
<ul id=’list’>
{state.items.map(item => (
<ListItem
id={item.id}
value={item.value}
completed={item.completed}
toggle={actions.toggle}
destroy={actions.destroy}
/>
))}
</ul>
<button onclick={() => actions.clearAllCompleted({ items: state.items }) }>
Clear completed items
</button>
</div>s
);

export default view;

First of all, this file uses the import declaration to import the h module from the Hyperapp library that we installed using npm earlier. This is the function that Hyperapp uses to create the Virtual DOM nodes that make up the view.
This file contains two components: AddItem and ListItem. These are just functions that return JSX code and are used to abstract different parts of the view into separate building blocks. If you find that you’re using a large number of components, it might be worth moving them into a separate components.js file and then importing them into the view.js file.
Notice that only the view function is exported at the end of the file. This means that only this function can be imported by other files, rather than the separate components.
Now we’ve added all our JavaScript code, we just need to piece it all together in the index.js file. This is done using the import directive. Add the following code to index.js:
import { app } from ‘hyperapp’

import state from ‘./js/state.js’
import actions from ‘./js/actions.js’
import view from ‘./js/view.js’

const main = app(state, actions, view, document.body);

This imports the app function from the Hyperapp library, then imports the three JavaScript files that we just created. The object or function that was exported from each of these files is assigned to the variables state,actions and view respectively, so they can be referenced in this file.
The last line of code calls the app function, which starts the app running. It uses each of the variables created from our imported files as the first three arguments. The last argument is the HTML element where the app will be rendered — which, by convention, is document.body.
The post Use Parcel to Bundle a Hyperapp App & Deploy to GitHub Pages appeared first on SitePoint.

Link: https://www.sitepoint.com/parcel-hyperapp-github-pages/

Build a To-do List with Hyperapp, the 1KB JS Micro-framework

In this tutorial, we’ll be using Hyperapp to build a to-do list app. If you want to learn functional programming principles, but not get bogged down in details, read on.
Hyperapp is hot right now. It recently surpassed 11,000 stars on GitHub and made the 5th place in the Front-end Framework section of the 2017 JavaScript Rising Stars. It was also featured on SitePoint recently, when it hit version 1.0.
The reason for Hyperapp’s popularity can be attributed to its pragmatism and ultralight size (1.4 kB), while at the same time achieving results similar to React and Redux out of the box.
So, What Is HyperApp?
Hyperapp allows you to build dynamic, single-page web apps by taking advantage of a virtual DOM to update the elements on a web page quickly and efficiently in a similar way to React. It also uses a single object that’s responsible for keeping track of the application’s state, just like Redux. This makes it easier to manage the state of the app and make sure that different elements don’t get out of sync with each other. The main influence behind Hyperapp was the Elm architecture.
At its core, Hyperapp has three main parts:

State. This is a single object tree that stores all of the information about the application.
Actions. These are methods that are used to change and update the values in the state object.
View. This is a function that returns virtual node objects that compile to HTML code. It can use JSX or a similar templating language and has access to the state and actions objects.

These three parts interact with each other to produce a dynamic application. Actions are triggered by events on the page. The action then updates the state, which then triggers an update to the view. These changes are made to the Virtual DOM, which Hyperapp uses to update the actual DOM on the web page.
Getting Started
To get started as quickly as possible, we’re going to use CodePen to develop our app. You need to make sure that the JavaScript preprocessor is set to Babel and the Hyperapp package is loaded as an external resource using the following link:
https://unpkg.com/hyperapp

To use Hyperapp, we need to import the app function as well as the h method, which Hyperapp uses to create VDOM nodes. Add the following code to the JavaScript pane in CodePen:
const { h, app } = hyperapp;

We’ll be using JSX for the view code. To make sure Hyperapp knows this, we need to add the following comment to the code:
/** @jsx h */

The app() method is used to initialize the application:
const main = app(state, actions, view, document.body);

This takes the state and actions objects as its first two parameters, the view() function as its third parameter, and the last parameter is the HTML element where the application is to be inserted into your markup. By convention, this is usually the tag, represented by document.body.
To make it easy to get started, I’ve created a boilerplate Hyperapp code template on CodePen that contains all the elements mentioned above. It can be forked by clicking on this link.
Hello Hyperapp!
Let’s have a play around with Hyperapp and see how it all works. The view() function accepts the state and actions objects as arguments and returns a Virtual DOM object. We’re going to use JSX, which means we can write code that looks a lot more like HTML. Here’s an example that will return a heading:
const view = (state, actions) => (
<h1>Hello Hyperapp!</h1>
);

This will actually return the following VDOM object:
{
name: “h1",
props: {},
children: "Hello Hyperapp!"
}

The view() function is called every time the state object changes. Hyperapp will then build a new Virtual DOM tree based on any changes that have occurred. Hyperapp will then take care of updating the actual web page in the most efficient way by comparing the differences in the new Virtual DOM with the old one stored in memory.
Components
Components are pure functions that return virtual nodes. They can be used to create reusable blocks of code that can then be inserted into the view. They can accept parameters in the usual way that any function can, but they don’t have access to the state and actions objects in the same way that the view does.
In the example below, we create a component called Hello() that accepts an object as a parameter. We extract the name value from this object using destructuring, before returning a heading containing this value:
const Hello = ({name}) => <h1>Hello {name}</h1>;

We can now refer to this component in the view as if it were an HTML element entitled <Hello />. We can pass data to this element in the same way that we can pass props to a React component:
const view = (state, actions) => (
<Hello name="Hyperapp" />
);

Note that, as we’re using JSX, component names must start with capital letters or contain a period.
State
The state is a plain old JavaScript object that contains information about the application. It’s the “single source of truth” for the application and can only be changed using actions.
Let’s create the state object for our application and set a property called name:
const state = {
name: "Hyperapp"
};

The view function now has access to this property. Update the code to the following:
const view = (state, actions) => (
<Hello name={state.name} />
);

Since the view can access the state object, we can use its name property as an attribute of the <Hello /> component.
The post Build a To-do List with Hyperapp, the 1KB JS Micro-framework appeared first on SitePoint.

Link: https://www.sitepoint.com/hyperapp-todo-list/

Introducing Axios, a Popular, Promise-based HTTP Client

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.
Making HTTP requests to fetch or save data is one of the most common tasks a client-side JavaScript application will need to do. Third-party libraries — especially jQuery — have long been a popular way to interact with the more verbose browser APIs, and abstract away any cross-browser differences.
As people move away from jQuery in favor of improved native DOM APIs, or front-end UI libraries like React and Vue.js, including it purely for its $.ajax functionality makes less sense.
Let’s take a look at how to get started using Axios in your code, and see some of the features that contribute to its popularity among JavaScript developers.
Axios vs Fetch
As you’re probably aware, modern browsers ship with the newer Fetch API built in, so why not just use that? There are several differences between the two that many feel gives Axios the edge.
One such difference is in how the two libraries treat HTTP error codes. When using Fetch, if the server returns a 4xx or 5xx series error, your catch() callback won’t be triggered and it is down to the developer to check the response status code to determine if the request was successful. Axios, on the other hand, will reject the request promise if one of these status codes is returned.
Another small difference, which often trips up developers new to the API, is that Fetch doesn’t automatically send cookies back to the server when making a request. It’s necessary to explicitly pass an option for them to be included. Axios has your back here.
One difference that may end up being a show-stopper for some is progress updates on uploads/downloads. As Axios is built on top of the older XHR API, you’re able to register callback functions for onUploadProgress and onDownloadProgress to display the percentage complete in your app’s UI. Currently, Fetch has no support for doing this.
Lastly, Axios can be used in both the browser and Node.js. This facilitates sharing JavaScript code between the browser and the back end or doing server-side rendering of your front-end apps.
Note: there are versions of the Fetch API available for Node but, in my opinion, the other features Axios provides give it the edge.
Installing
As you might expect, the most common way to install Axios is via the npm package manager:
npm i axios

and include it in your code where needed:
// ES2015 style import
import axios from ‘axios’;

// Node.js style require
const axios = require(‘axios’);

If you’re not using some kind of module bundler (e.g. webpack), then you can always pull in the library from a CDN in the traditional way: