4 Essential ES2015 Features for Vue.js Development

ES2015 (aka ES6) is the current specification of the JavaScript language. If you’re new to JavaScript or haven’t updated your JavaScript knowledge recently, there are a number of new features in ES2015 that make development much better and more enjoyable.
If you’re a Vue developer, you’d benefit from learning all these new features. But as a means of triage, you might start with those features that apply to Vue specifically.

Link: https://dzone.com/articles/4-essential-es2015-features-for-vuejs-development

How to Build a Serverless, CMS-powered Angular Application

Angular has taken off in popularity and is in widespread use. Developed and maintained by Google engineers, Angular has found a place all across dynamic web applications and is an increasingly in-demand platform.
Angular offers the advantages of a large and enthusiastic community and outstanding MVC that doesn’t require developers to spend valuable time writing code to put multiple MVC components back together again. In short, Angular is a robust and comprehensive web application framework for front-end development that is unit-testing ready, making it the tool of choice for many developers.
If you’re using Angular, you may run into the need for content management capability — a blog being one example. Adding a CMS to an Angular app may seem daunting, especially if you’re trying to integrate it into a traditional CMS like WordPress, but there’s a new breed of API-based CMS that greatly simplifies things. ButterCMS is one example of a SaaS-based headless CMS that provides a hosted CMS dashboard and content API that you query from your Angular application. This means you don’t need to spin up any new infrastructure to add a CMS to your Angular app.
This tutorial will demonstrate how to build a CMS-powered Angular application that has marketing pages (customer case studies), a blog, and FAQ, all powered via an API. No servers needed!
Installation
First, you’ll get started by installing the Angular CLI.
npm install -g @angular/cli

Set up a new Angular project using Angular CLI. By default, Angular CLI uses CSS styling, so adding the –style=scss flag tells Angular CLI to use SCSS instead:
ng new hello-buttercms-project –style=scss
cd hello-buttercms-project

Install Angular Material and Angular Material related package:
npm install –save @angular/material @angular/cdk
npm install –save @angular/animations

Install ButterCMS. Run this in your command line:
npm install buttercms –save

Butter can also be loaded using a CDN:
<script src=”https://cdnjs.buttercms.com/buttercms-1.1.1.min.js"></script>

Quickly Get Started
Open the project in your code editor of choice. Under src/app create a directory called _services.
We create a file called butterCMS.service.js. This allows us to have your API Token in one place and not accidentally alter it.
import * as Butter from ‘buttercms’;

export const butterService = Butter(‘b60a008584313ed21803780bc9208557b3b49fbb’);

You’ll import this file into any component we want to use ButterCMS.
For a Quickstart, go to src/app/hello-you/hello-you.component.ts and import butterService:
import {butterService} from ‘../_services’;

Inside the HelloYouComponent create methods:
fetchPosts() {
butter.post.list({
page: 1,
page_size: 10
})
.then((res) => {
console.log(‘Content from ButterCMS’)
console.log(res)
})
}

Now call this method when the component is loaded by adding it to the OnInit lifecycle hook:
ngOnInit() {
this.fetchPosts();
}

This API request fetches your blog posts. Your account comes with one example post, which you’ll see in the response.
Next, create another method to retrieve the Homepage Headline Content Field:
fetchHeadline() {
butter.content.retrieve([‘homepage_headline’])
.then((res) => {
console.log(‘Headline from ButterCMS’)
console.log(res)
})
}

Add this method to the OnInit lifecycle hook.
ngOnInit() {
this.fetchPosts();
this.fetchHeadline();
}

This API request fetches homepage headline content. You can set up your own custom content fields to manage any kind of content you need.
Add Marketing Pages
Setting up CMS-powered pages is a simple, three-step process:

Define the Page Type
Create a page
Integrate into your application

Define Page
First, create a Page Type to represent your Customer Case Study pages. Next, define the fields you want for your customer case studies. With your Page Type defined, you can now create the first case study page. Specify the name and URL of the page, and then populate the content of the page.
With your page defined, the ButterCMS API will return it in JSON format like this:
Continue reading %How to Build a Serverless, CMS-powered Angular Application%

Link: https://www.sitepoint.com/how-to-build-a-serverless-cms-powered-angular-application/

Adding Font Awesome to a Yeoman Generated JET Project

Oracle JET, Oracle’s JavaScript toolkit for single page apps, includes over 80 components to help build enterprise JavaScript applications. But one thing JET doesn’t include is a set of icons – the argument being that different apps and teams will likely choose different icons. Luckily, it’s not too difficult to add Font Awesome to a JET app. If you’re using one of the starter apps without the Yeoman generator, have a look at Paul Thaden’s post on adding Font Awesome. In this post, I’ll show you how to add Font Awesome to a project created via the Yeoman generator.
For those who haven’t used it, Yeoman is a scaffolding tool designed to help kickstart new projects by running scripts called generators. Generators are often used to create opinionated starter apps with best practices and build scripts built in. The JET generator installs a sample app and includes a Grunt-based build system that can be customized as needed.

Link: https://dzone.com/articles/adding-font-awesome-to-a-yeoman-generated-jet-proj?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Introduction to the Fetch API

In this article, we’ll learn what the new Fetch API looks like, what problems it solves, and the most practical way to retrieve remote data inside your web page using the fetch() function.
For years, XMLHttpRequest has been web developers’ trusted sidekick. Whether directly or under the hood, XMLHttpRequest has enabled Ajax and a whole new type of interactive experience, from Gmail to Facebook.
However, XMLHttpRequest is slowly being superseded by the Fetch API. Both can be used to make network requests, but the Fetch API is Promise-based, which enables a cleaner, more concise syntax and helps keep you out of callback hell.
The Fetch API
The Fetch API provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request.
The fetch method only has one mandatory argument, which is the URL of the resource you wish to fetch. A very basic example would look something like the following. This fetches the top five posts from r/javascript on Reddit:
fetch(‘https://www.reddit.com/r/javascript/top/.json?limit=5’)
.then(res => console.log(res));

If you inspect the response in your browser’s console, you should see a Response object with several properties:
{
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: “"
type: "cors"
url: "https://www.reddit.com/top/.json?count=5"
}

It seems that the request was successful, but where are our top five posts? Let’s find out.
Loading JSON
We can’t block the user interface waiting until the request finishes. That’s why fetch() returns a Promise, an object which represents a future result. In the above example, we’re using the then method to wait for the server’s response and log it to the console.
Now let’s see how we can extract the JSON payload from that response once the request completes:
fetch(‘https://www.reddit.com/r/javascript/top/.json?limit=5’)
.then(res => res.json())
.then(json => console.log(json));

We start the request by calling fetch(). When the promise is fulfilled, it returns a Response object, which exposes a json method. Within the first then() we can call this json method to return the response body as JSON.
However, the json method also returns a promise, which means we need to chain on another then(), before the JSON response is logged to the console.
And why does json() return a promise? Because HTTP allows you to stream content to the client chunk by chunk, so even if the browser receives a response from the server, the content body might not all be there yet!
Async … await
The .then() syntax is nice, but a more concise way to process promises in 2018 is using async … await — a new syntax introduced by ES2017. Using async Ú await means that we can mark a function as async, then wait for the promise to complete with the await keyword, and access the result as a normal object. Async functions are supported in all modern browsers (not IE or Opera Mini) and Node.js 7.6+.
Here’s what the above example would look like (slightly expanded) using async … await:
async function fetchTopFive(sub) {
const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
const fetchResult = fetch(URL)
const response = await fetchResult;
const jsonData = await response.json();
console.log(jsonData);
}

fetchTopFive(‘javascript’);

Not much has changed. Apart from the fact that we’ve created an async function, to which we’re passing the name of the subreddit, we’re now awaiting the result of calling fetch(), then using await again to retrieve the JSON from the response.
That’s the basic workflow, but things involving remote services doesn’t always go smoothly.
Continue reading %Introduction to the Fetch API%

Link: https://www.sitepoint.com/introduction-to-the-fetch-api/

JavaScript and Underscore.js Type Methods in PHP

I’ve been working with PHP since 2000 and with JavaScript even longer. Over the last decade, JavaScript has evolved drastically. It had a promising design from the very beginning and gained its current incredible shape with the shift to ES2015 (Harmony). PHP, though, didn’t change that much. Apparently, it’s doomed always to suffer from its own legacy. It arrived in the mid-90s as a simple CGI app to maintain Rasmus Lerdorf’s home page and have been more like spontaneously developing ever since. That resulted in syntax inconsistency, a mix of functional and OOP-based assets, and absence of a decent language specification. So every time I switch to PHP I miss the rationality, predictability, and flexibility of JavaScript. This made me consider a library which would bring a JavaScript-like development experience to PHP. Eventually, I came up with Extras, which extends PHP types with JavaScript (other than Underscore) methods, unlocks chaining, and introduces the PlainObject type representing an object-literal.
JavaScript Meets PHP
The library enriches with JavaScript and Underscore.js methods the following PHP types: array (both sequential and associative), string, number (integer, float, NaN), function (callable), collection (Iterable, ArrayObject, Iterator) and boolean. Every added method is a static method of the class representing the type. So we can access any directly, without the creation of a chain like Arrays::map.

Link: https://dzone.com/articles/javascript-and-underscorejs-type-methods-in-php?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

ES6 Generators and Iterators: a Developer’s Guide

ES6 brought a number of new features to the JavaScript language. Two of these features, generators and iterators, have substantially changed how we write specific functions in more complex front-end code.
While they do play nicely with each other, what they actually do can be a little confusing, so let’s check them out.
Iterators
Iteration is a common practice in programming and is usually used to loop over a set of values, either transforming each value, or using or saving it in some way for later.
In JavaScript, we’ve always had for loops that look like this:
for (var i = 0; i < foo.length; i++){ // do something with i } But ES6 gives us an alternative: for (const i of foo) { // do something with i } This is arguably way cleaner and easier to work with, and reminds me of languages like Python and Ruby. But there’s something else that’s pretty important to note about this new kind of iteration: it allows you to interact with elements of a data set directly. Imagine that we want to find out if each number in an array is prime or not. We could do this by coming up with a function that does exactly that. It might look like this: function isPrime(number) { if (number < 2) { return false; } else if (number === 2) { return true; } for (var i = 2; i < number; i++) { if (number % i === 0) { return false; break; } } return true; } Not the best in the world, but it works. The next step would be to loop over our list of numbers and check whether each one is prime with our shiny new function. It’s pretty straightforward: var possiblePrimes = [73, 6, 90, 19, 15]; var confirmedPrimes = []; for (var i = 0; i < possiblePrimes.length; i++) { if (isPrime(possiblePrimes[i])) { confirmedPrimes.push(possiblePrimes[i]); } } // confirmedPrimes is now [73, 19] Again, it works, but it’s clunky and that clunkiness is largely down to the way JavaScript handles for loops. With ES6, though, we’re given an almost Pythonic option in the new iterator. So the previous for loop could be written like this: const possiblePrimes = [73, 6, 90, 19, 15]; const confirmedPrimes = []; for (const i of possiblePrimes){ if ( isPrime(i) ){ confirmedPrimes.push(i); } } // confirmedPrimes is now [73, 19] This is far cleaner, but the most striking bit of this is the for loop. The variable i now represents the actual item in the array called possiblePrimes. So, we don’t have to call it by index anymore. This means that instead of calling possiblePrimes[i] in the loop, we can just call i. Behind the scenes, this kind of iteration is making use of ES6’s bright and shiny Symbol.iterator() method. This bad boy is in charge of describing the iteration and, when called, returns a JavaScript object containing the next value in the loop and a done key that is either true or false depending on whether or not the loop is finished. In case you’re interested in this sort of detail, you can read more about it on this fantastic blog post titled Iterators gonna iterate by Jake Archibald. It’ll also give you a good idea of what’s going on under the hood when we dive into the other side of this article: generators. Continue reading %ES6 Generators and Iterators: a Developer’s Guide%

Link: https://www.sitepoint.com/ecmascript-2015-generators-and-iterators/

How to Update Angular Projects to the Latest Version

In this article, we’ll look at how to update Angular projects to the latest version.
This article is part 6 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

Part 0 — The Ultimate Angular CLI Reference Guide
Part 1 — Getting our first version of the Todo application up and running
Part 2 — Creating separate components to display a list of todos and a single todo
Part 3 — Update the Todo service to communicate with a REST API
Part 4 — Use Angular router to resolve data
Part 5 — Add authentication to protect private content
Part 6 — How to Update Angular Projects to the latest version.

In part 1 we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine but, unfortunately, the whole app was crammed into a single component.
In part 2 we examined a more modular component architecture and learned how to break this single component into a structured tree of smaller components that are easier to understand, reuse and maintain.
In part 3 we updated our application to communicate with a REST API backend using RxJS and Angular’s HTTP service.
In part 4, we introduced Angular Router and learned how the router updates our application when the browser URL changes and how we can use the router to resolve data from our backend API.
In part 5, we added authentication to our application and learned how we can protect sections from our application from unauthorized access.
Don’t worry! You don’t need to have followed part 1, 2, 3, 4 or 5 of this tutorial for 6 to make sense. You can simply grab a copy of our repo, check out the code from part 5, and use that as a starting point. This is explained in more detail below.
Up and Running
To start on our goal to update Angular, make sure you have the latest version of the Angular CLI installed. If you don’t, you can install it with the following command:
npm install -g @angular/cli@latest

If you need to remove a previous version of the Angular CLI, you can:
npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that, you’ll need a copy of the code from part 5. This is available on GitHub. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.
The code that we ended with in part 5 and that we start with in this article is tagged as part-5. The code that we end this article with is tagged as part-6.
You can think of tags like an alias to a specific commit ID. You can switch between them using git checkout. You can read more on that here.
So, to get up and running (with the latest version of the Angular CLI installed) we would do this:
git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
git checkout part-5
npm install
ng serve

Then visit http://localhost:4200/. If all’s well, you should see the working Todo app.
Update Angular: Our Plan of Attack
In this article, as we update Angular, we’ll learn the following:

how Angular versions work
where to find instructions on how to update Angular
how to update our code from Angular 4 to Angular 5 (Angular 5 being the latest version at time of writing).

By the end of this article, you’ll understand:

the underlying meaning of specific Angular versions
where to find exact instructions on how to update Angular applications
how to figure out which code changes are required (if any) for Angular 5.

Let’s get started!
The Meaning of Angular Versions
To support a thriving ecosystem, Angular needs to be both stable and evolutionary.
On one hand, Angular aims to provide developers with maximum stability for mission-critical applications. On the other hand, it constantly needs to adapt and advance to support the latest changes in web technologies.
Therefore, the Angular team has decided to use a time-based release cycle with semantic versioning.
A time-based release cycle means that we can expect new versions of Angular (Angular 5, Angular 6, Angular 7, etc.) every couple of weeks or months.
Semantic versioning means that the version number of Angular allows us to predict whether or not it will break our application if we upgrade to it.
In essence, a semantic version looks like this: Major.Minor.Patch.
So version v1.3.8 has a major component with a value of 1, a minor component with a value of 3 and a patch component with a value of 1.
When a new version is released, the new version implicitly indicates the type of change that was made to the code.
The following rules are applied when a semantic version is increased:

Each increment happens numerically with an increment of 1.

When a bug is fixed and the code stays backwards compatible, the patch component is increased:
v0.0.3 // Before bugfix
v0.0.4 // After bugfix

When functionality is added and the code stays backwards compatible, the minor component is increased and the patch component is reset to zero:
v0.2.4 // Before addition of new functionality
v0.3.0 // After addition of new functionality

When a change is implemented that causes the code to become backwards incompatible, also known as a breaking change, the major component is increased and the minor and patch components are reset to zero:
v7.3.5 // Before implementing backwards incompatible changes
v8.0.0 // After implementing backwards incompatible changes

If you’re not familiar with semantic versioning, make sure to check out this simple guide to semantic versioning.
The Angular team combines semantic versioning with a time-based release cycle to aim at:

a new patch release every week
a new minor release every month
a new major release every 6 months

The release schedule is not set in stone, as there may be holidays or special events, but it’s a good indicator of what we can expect in terms of upcoming versions.
You can follow the official Angular blog and the official change log to stay up to date on the latest developments.
A huge benefit of semantic versions is that we can safely update Angular applications with patch or minor releases without having to worry about breaking our applications.
But what if there’s a new major release?
The Angular Update Guide
We already learned that a major release can come with breaking changes. So how do we know if our existing application will break or not if we update it?
One way would be to read the official change log and go through the list of changes.
A much easier way is to use the Angular Update Guide to update Angular. You select your current version of Angular and the version you wish to upgrade to and the application tells you the exact steps you need to take:

For our Angular Todo application, we wish to upgrade from Angular 4.0 to Angular 5.0.
Let’s select app complexity level Advanced so we see all the possible measures we need to take:

We get a complete overview of all the steps we need to take to update our application.
How sweet is that!
Before Updating
The Before Updating list contains 12 items. None of the items apply to our Angular Todo application, so we can safely proceed to the next step.
During the Update
From the During the Update list, only the last item applies to our application. We need to update our dependencies, so let’s run the proposed commands in the root of our project:
$ npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@’^5.0.0′ typescript@2.4.2 rxjs@’^5.5.2′

$ npm install typescript@2.4.2 –save-exact

Because we updated our Angular CLI to the latest version in the Up and Running section, we also update our local version:
$ npm install @angular/cli@latest –save-dev

To verify that our application runs correctly, we run:
$ ng serve

If ng serve fails to start, try deleting your node_modules directory and package-lock.json file and run npm install to recreate a clean node_modules directory and package-lock.json file.
Continue reading %How to Update Angular Projects to the Latest Version%

Link: https://www.sitepoint.com/update-angular-projects/

ES6 Arrow Functions: Fat and Concise Syntax in JavaScript

Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope. Surveys show they’re the most popular ES6 feature:

Source: Axel Rauschmayer survey on favorite ES6 features

Source: Ponyfoo’s survey on the most commonly used ES6 features
The good news is that many major modern browsers support the use of arrow functions.
This post will cover the details of arrow functions — how to use them, common syntaxes, common use cases, and gotchas/pitfalls.
What Are Arrow Functions?
Arrow functions – also called “fat arrow” functions, from CoffeeScript (a transcompiled language) — are a more concise syntax for writing function expressions. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way this binds in functions.
Arrow functions make our code more concise, and simplify function scoping and the this keyword. They are one-line mini functions which work much like Lambdas in other languages like C# or Python. (See also lambdas in JavaScript). By using arrow functions, we avoid having to type the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.
Using Arrow Functions
There are a variety of syntaxes available in arrow functions, of which MDN has a thorough list. We’ll cover the common ones here to get you started. Let’s compare how ES5 code with function expressions can now be written in ES6 using arrow functions.
Basic Syntax with Multiple Parameters (from MDN)
// (param1, param2, paramN) => expression

// ES5
var multiplyES5 = function(x, y) {
return x * y;
};

// ES6
const multiplyES6 = (x, y) => { return x * y };

Code Example at JSBin.
The arrow function example above allows a developer to accomplish the same result with fewer lines of code and approximately half the typing.
Curly brackets aren’t required if only one expression is present. The preceding example could also be written as:
const multiplyES6 = (x, y) => x * y;

Basic Syntax with One Parameter
Parentheses are optional when only one parameter is present
//ES5
var phraseSplitterEs5 = function phraseSplitter(phrase) {
return phrase.split(‘ ‘);
};

//ES6
const phraseSplitterEs6 = phrase => phrase.split(” ");

console.log(phraseSplitterEs6("ES6 Awesomeness")); // ["ES6", "Awesomeness"]

Code Example at JSBin.
No Parameters
Parentheses are required when no parameters are present.
//ES5
var docLogEs5 = function docLog() {
console.log(document);
};

//ES6
var docLogEs6 = () => { console.log(document); };
docLogEs6(); // #document… ….

Code Example at JSBin.
Object Literal Syntax
Arrow functions, like function expressions, can be used to return an object literal expression. The only caveat is that the body needs to be wrapped in parentheses, in order to distinguish between a block and an object (both of which use curly brackets).
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};

// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });

console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}

Code Example at JSBin.
Use Cases for Arrow Functions
Now that we’ve covered the basic syntaxes, let’s get into how arrow functions are used.
One common use case for arrow functions is array manipulation and the like. It’s common that you’ll need to map or reduce an array. Take this simple array of objects:
const smartPhones = [
{ name:’iphone’, price:649 },
{ name:’Galaxy S6′, price:576 },
{ name:’Galaxy Note 5′, price:489 }
];

We could create an array of objects with just the names or prices by doing this in ES5:
// ES5
var prices = smartPhones.map(function(smartPhone) {
return smartPhone.price;
});

console.log(prices); // [649, 576, 489]

An arrow function is more concise and easier to read:
// ES6
const prices = smartPhones.map(smartPhone => smartPhone.price);
console.log(prices); // [649, 576, 489]

Code Example at JSBin.
Here’s another example using the array filter method:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

// ES5
var divisibleByThrreeES5 = array.filter(function (v){
return v % 3 === 0;
});

// ES6
const divisibleByThrreeES6 = array.filter(v => v % 3 === 0);

console.log(divisibleByThrreeES6); // [3, 6, 9, 12, 15]

Code Example at JSBin.
Continue reading %ES6 Arrow Functions: Fat and Concise Syntax in JavaScript%

Link: https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/