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:
.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: ""

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:
.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 = `${sub}/top/.json?limit=5`;
const fetchResult = fetch(URL)
const response = await fetchResult;
const jsonData = await response.json();


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%


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.
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%


Game AI: The Bots Strike Back!

The following is a short extract taken from our new book, HTML5 Games: Novice to Ninja, written by Earle Castledine. Access to the book is included with SitePoint Premium membership, or you can grab a copy in stores worldwide. You can check out a free sample of the first chapter here.
We have all the tools at our disposal now to make fantastically detailed worlds to explore and inhabit. Unfortunately, our co-inhabitants haven’t proved themselves to be very worthy opponents. They’re dumb: they show no emotion, no thought, no anima. We can instill these characteristics via graphics, animation, and above all, artificial intelligence (AI).
Artificial intelligence is a huge and extremely complex field. Luckily, we can get impressive results even with a lot more artificial than intelligence. A couple of simple rules (combined with our old friend Math.random) can give a passable illusion of intention and thought. It doesn’t have to be overly realistic as long as it supports our game mechanics and is fun.
Like collision detection, AI is often best when it’s not too good. Computer opponents are superhuman. They have the gift of omniscience and can comprehend the entire state of the world at every point in time. The poor old human player is only able to see what’s visible on the screen. They’re generally no match against a computer.
But we don’t let them know that! They’d feel bad, question the future of humanity, and not want to play our games. As game designers, it’s our job to balance and dictate the flow of our games so that they’re always fair, challenging, and surprising to the player.
Intentional Movement
Choosing how sprites move around in the game is great fun. The update function is your blank canvas, and you get godlike control over your entities. What’s not to like about that!
The way an entity moves is determined by how much we alter its x and y position every frame (“move everything a tiny bit!”). So far, we’ve moved things mostly in straight lines with pos.x += speed * dt. Adding the speed (times the delta) causes the sprite to move to the right. Subtracting moves it to the left. Altering the y coordinate moves it up and down.
To make straight lines more fun, inject a bit of trigonometry. Using pos.y += Math.sin(t * 10) * 200 * dt, the sprite bobs up and down through a sine wave. t * 10 is the frequency of the wave. t is the time in seconds from our update system, so it’s always increasing linearly. Giving that to Math.sin produces a smooth sine wave. Changing the multiplier will alter the frequency: a lower number will oscillate faster. 200 is the amplitude of the waves.
You can combine waves to get even more interesting results. Say you added another sine wave to the y position: pos.y += Math.sin(t * 11) * 200 * dt. It’s almost exactly the same as the first, but the frequency is altered very slightly. Now, as the two waves reinforce and cancel each other out as they drift in and out of phase, the entity bobs up and down faster and slower. Shifting the frequency and amplitude a lot can give some interesting bouncing patterns. Alter the x position with Math.cos and you have circles.
The important aspect of this is that movements can be combined to make more complex-looking behaviors. They can move spasmodically, they can drift lazily. As we go through this chapter, they’ll be able to charge directly towards a player, or to run directly away. They’ll be able to traverse a maze. When you combine these skills (a bobbing motion used in conjunction with a charge-at-player), or sequence them (run away for two seconds, then bob up and down for one second) they can be sculpted into very lifelike beings.
We need to spice up these apathetic ghosts and bats, giving them something to live for. We’ll start with the concept of a “waypoint”. Waypoints are milestones or intermediate target locations that the entity will move towards. Once they arrive at the waypoint, they move on to the next, until they reach their destination. A carefully placed set of waypoints can provide the game character with a sense of purpose, and can be used to great effect in your level design.

Continue reading %Game AI: The Bots Strike Back!%


An Introduction to Functional JavaScript

You’ve heard that JavaScript is a functional language, or at least that it’s capable of supporting functional programming. But what is functional programming? And for that matter, if you’re going to start comparing programming paradigms in general, how is a functional approach different from the JavaScript that you’ve always written?
Well, the good news is that JavaScript isn’t picky when it comes to paradigms. You can mix your imperative, object-oriented, prototypal, and functional code as you see fit, and still get the job done. But the bad news is what that means for your code. JavaScript can support a wide range of programming styles simultaneously within the same codebase, so it’s up to you to make the right choices for maintainability, readability, and performance.
Functional JavaScript doesn’t have to take over an entire project in order to add value. Learning a little about the functional approach can help guide some of the decisions you make as you build your projects, regardless of the way you prefer to structure your code. Learning some functional patterns and techniques can put you well on your way to writing cleaner and more elegant JavaScript regardless of your preferred approach.
Imperative JavaScript
JavaScript first gained popularity as an in-browser language, used primarily for adding simple hover and click effects to elements on a web page. For years, that’s most of what people knew about it, and that contributed to the bad reputation JavaScript earned early on.
As developers struggled to match the flexibility of JavaScript against the intricacy of the browser document object model (DOM), actual JavaScript code often looked something like this in the real world:
[code language=”js"]
var result;
function getText() {
var someText = prompt("Give me something to capitalize");
alert(result.join(" "));
function capWords(input) {
var counter;
var inputArray = input.split(" ");
var transformed = "";
result = [];
for (counter = 0; counter < inputArray.length; counter++) { transformed = [ inputArray[counter].charAt(0).toUpperCase(), inputArray[counter].substring(1) ].join(""); result.push(transformed); } }; document.getElementById("main_button").onclick = getText; [/code] So many things are going on in this little snippet of code. Variables are being defined on the global scope. Values are being passed around and modified by functions. DOM methods are being mixed with native JavaScript. The function names are not very descriptive, and that’s due in part to the fact that the whole thing relies on a context that may or may not exist. But if you happened to run this in a browser inside an HTML document that defined a <button id="main_button">, you might get prompted for some text to work with, and then see the an alert with first letter of each of the words in that text capitalized.
Imperative code like this is written to be read and executed from top to bottom (give or take a little variable hoisting). But there are some improvements we could make to clean it up and make it more readable by taking advantage of JavaScript’s object-oriented nature.
Continue reading %An Introduction to Functional JavaScript%


JavaScript Functions That Define and Rewrite Themselves

The following is a short extract from our new book, JavaScript: Novice to Ninja, 2nd Edition, written by Darren Jones. It’s the ultimate beginner’s guide to JavaScript. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.
The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.
Consider the following function:
function party(){
console.log(‘Wow this is amazing!’);
party = function(){
console.log(‘Been there, got the T-Shirt’);

This logs a message in the console, then redefines itself to log a different message in the console. When the function has been called once, it will be as if it was defined like this:
function party() {
console.log(‘Been there, got the T-Shirt’);

Every time the function is called after the first time, it will log the message “Been there, got the T-Shirt”:
<< 'Wow this is amazing!' party(); << 'Been there, got the T-Shirt' party(); << 'Been there, got the T-Shirt' If the function is also assigned to another variable, this variable will maintain the original function definition and not be rewritten. This is because the original function is assigned to a variable, then within the function, a variable with the same name as the function is assigned to a different function. You can see an example of this if we create a variable called beachParty that is assigned to the party() function before it is called for the first time and redefined: function party(){ console.log('Wow this is amazing!'); party = function(){ console.log('Been there, got the T-Shirt'); } } const beachParty = party; // note that the party function has not been invoked beachParty(); // the party() function has now been redefined, even though it hasn't been called explicitly << 'Wow this is amazing!' party(); << 'Been there, got the T-Shirt' beachParty(); // but this function hasn't been redefined << 'Wow this is amazing!' beachParty(); // no matter how many times this is called it will remain the same << 'Wow this is amazing!' Losing Properties Be careful: if any properties have previously been set on the function, these will be lost when the function redefines itself. In the previous example, we can set a music property, and see that it no longer exists after the function has been invoked and redefined: function party() { console.log('Wow this is amazing!'); party = function(){ console.log('Been there, got the T-Shirt'); } } = 'Classical Jazz'; // set a property of the function party(); << "Wow this is amazing!"; // function has now been redefined, so the property doesn't exist << undefined This is called the Lazy Definition Pattern and is often used when some initialization code is required the first time it’s invoked. This means the initialization can be done the first time it’s called, then the function can be redefined to what you want it to be for every subsequent invocation. Init-Time Branching This technique can be used with the feature detection that we discussed in the last chapter to create functions that rewrite themselves, known as init-time branching. This enables the functions to work more effectively in the browser, and avoid checking for features every time they’re invoked. Let’s take the example of our fictional unicorn object that’s yet to have full support in all browsers. In the last chapter, we looked at how we can use feature detection to check if this is supported. Now we can go one step further: we can define a function based on whether certain methods are supported. This means we only need to check for support the first time the function is called: function ride(){ if (window.unicorn) { ride = function(){ // some code that uses the brand new and sparkly unicorn methods return 'Riding on a unicorn is the best!'; } } else { ride = function(){ // some code that uses the older pony methods return 'Riding on a pony is still pretty good'; } } return ride(); } After we’ve checked whether the window.unicorn object exists (by checking to see if it’s truthy), we’ve rewritten the ride() function according to the outcome. Right at the end of the function, we call it again so that the rewritten function is now invoked, and the relevant value returned. One thing to be aware of is that the function is invoked twice the first time, although it becomes more efficient each subsequent time it’s invoked. Let’s take a look at how it works: Continue reading %JavaScript Functions That Define and Rewrite Themselves%


Hello, World! Your First JavaScript Programs

The following is a short extract from our new book, JavaScript: Novice to Ninja, 2nd Edition, written by Darren Jones. It’s the ultimate beginner’s guide to JavaScript. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.
It is a tradition when learning programming languages to start with a “Hello, world!" program. This is a simple program that outputs the phrase "Hello world!" to announce your arrival to the world of programming. We’re going to stick to this tradition and write this type of program in JavaScript. It will be a single statement that logs the phrase "Hello, world!" to the console.
To get started, you’ll need to open up your preferred console (either the Node REPL, browser console, or ES6 Console on the web). Once the console has opened, all you need to do is enter the following code:
console.log(‘Hello world!’);

Then press Enter. if all went to plan you should see an output of "Hello, world!" displayed; similar to the screenshot below.

Congratulations, you’ve just written your first JavaScript program! It might not look like much, but a wise person once said that every ninja programmer’s journey begins with a single line of code (or something like that, anyway!).
JavaScript in the Browser
JavaScript is an interpreted language and needs a host environment to run. Because of its origins, the main environment that JavaScript runs in is the browser, although it can be run in other environments; for example, our first program that we just wrote ran in the Node REPL. Node can also be used to run JavaScript on a server. By far the most common use of JavaScript is still to make web pages interactive. Because of this, we should have a look at what makes up a web page before we go any further.
Three Layers of the Web
Nearly all web pages are made up of three key ingredients ― HTML, CSS and JavaScript. HTML is used to mark up the content. CSS is the presentation layer, and JavaScript adds the interactivity.
Each layer builds on the last. A web page should be able to function with just the HTML layer ― in fact, many websites celebrate “naked day” when they remove the CSS layer from their site. A website using just the HTML layer will be in its purest form and look very old school, but should still be fully functional.

Keep These Layers Separate

It is widely considered best practice to separate the concerns of each layer, so each layer is only responsible for one thing. Putting them altogether can lead to very complicated pages where all of the code is mixed up together in one file, causing “tag soup” or “code spaghetti”. This used to be the standard way of producing a website and there are still plenty of examples on the web that do this.

Unobtrusive JavaScript
When JavaScript was initially used, it was designed to be inserted directly into the HTML code, as can be seen in this example that will display a message when a button is clicked:

Learning JavaScript: 9 Common Mistakes That Are Holding You Back

A lot of people try to learn JavaScript and then give up. Then they tell themselves things like, “JavaScript is too confusing," or worse, "Maybe I’m not cut out for web development."
The sad part? There was no need to give up. All that was needed was a different learning approach.
In this article, we’ll cover some of the most common learning mistakes people make and find out how to avoid them. Many of these tips will be applicable outside of JavaScript or even web development, so there’s that bonus too.
Let’s dive in!
Mistake #1: Overanalyzing Instead of Getting Started
It can be tempting to look for all the information you can get before you start learning JavaScript. If you look, you’ll find information about how JavaScript is the best thing ever or the worst thing ever, or that you need to be on this framework or that framework. You might also hear that you need to write JavaScript a certain way or else you’ll never be a "real" developer.
Whether or not these points have validity, nothing is worse than the six months to a year you’ll waste agonizing instead of starting.
Just type one line of code. It doesn’t have to be perfect. It can be terrible. If you get started, you’ve already passed one of the hurdles that stop a lot of people.
Mistake #2: Learning a Framework Before Learning Plain JavaScript
JavaScript frameworks are built on top of vanilla JavaScript, so if you understand JavaScript, you automatically understand the fundamentals of how to use any JavaScript framework.
However, if you jump straight into a framework, you’ll end up memorizing without understanding. It’s like trying to write sentences without knowing what words mean. You’ll end up memorizing random phrases instead of understanding how words work and how to put them together to make your own sentences.
If you go straight to a framework it’ll be harder to learn and you’ll have a harder time adapting to another framework if you need to. If you learn plain JavaScript first, you have a firm basis to understand all the frameworks.
Mistake #3: Moving to the Next Step Too Soon
One of the most common mistakes is to move on immediately after understanding a concept.
I’ve definitely struggled with this one because it’s tempting to move forwards once you understand something.
What helped was to treat each concept like a new toy; That means taking some time to enjoy what you just learned. Play around, experiment, see if you can do something new with it. You’ll learn a lot that way, and you’ll remember better as well.
Once you feel like you can apply a concept in your sleep, move on. It takes a little bit more time up front, but soon it makes everything go much faster.
On the other hand, if you rush, you’ll end up forgetting and having to backtrack for every little thing. That ends up taking way more time, and it can be discouraging. In fact, this is a common reason people have said they quit JavaScript.
Mistake #4: Not Breaking Concepts Into Small Enough Pieces
Learning is like a staircase: If you can take one step, you can keep taking more steps until you reach your goals. When something is tough to understand, it’s often because you’re trying to take a flying leap instead of going one step at a time. Of course, it seems impossible!
Continue reading %Learning JavaScript: 9 Common Mistakes That Are Holding You Back%


10 Languages That Compile to JavaScript

Modern applications have different requirements than simple websites. But the browser is a platform with a (mostly) fixed set of technologies available, and JavaScript remains as the core language for web applications; any application that needs to run in the browser has to be implemented in that language.
We all know that JavaScript is not the best language for every task, and when comes to complex applications, it might fall short. To avoid this problem, several new languages and transpilers of existing ones have been created, all of them producing code that can work in the browser without writing any line of JavaScript and without thinking about the limitations of the language.
This article includes a list of ten interesting languages that can be transpiled to JavaScript to be executed in the browser or on a platform like Node.js.
Dart is a classical, object-oriented language where everything is an object and any object is an instance of a class (objects can act as functions too.) It is specially made to build applications for browsers, servers, and mobile devices. It is maintained by Google and is the language that powers the next generation AdWords UI, the most important product of Google regarding revenue, which is in itself a proof of its power at scale.
The language can be translated to JavaScript to be used in a browser, or be directly interpreted by the Dart VM, which allows you to build server applications too. Mobile applications can be made using the Flutter SDK.
Complex applications also require a mature set of libraries and language features specially designed for the task, and Dart includes all of this. An example of a popular library is AngularDart, a version of Angular for Dart.
It allows you to write type-safe code without being too intrusive; you can write types, but you are not required to do so since they can be inferred. This allows for rapid prototyping without having to overthink the details, but once you have something working, you can add types to make it more robust.
Regarding concurrent programming in the VM, instead of shared-memory threads (Dart is single-threaded), Dart uses what they call Isolates, with their own memory heap, where communication is achieved using messages. In the browser, the story is a little different: instead of creating new isolates, you create new Workers.
// Example extracted from

import ‘dart:async’;
import ‘dart:math’ show Random;

main() async {
print(‘Compute π using the Monte Carlo method.’);
await for (var estimate in computePi()) {
print(‘π ≅ $estimate’);

/// Generates a stream of increasingly accurate estimates of π.
Stream computePi({int batch: 1000000}) async* {
var total = 0;
var count = 0;
while (true) {
var points = generateRandom().take(batch);
var inside = points.where((p) => p.isInsideUnitCircle);
total += batch;
count += inside.length;
var ratio = count / total;
// Area of a circle is A = π⋅r², therefore π = A/r².
// So, when given random points with x ∈ <0,1>,
// y ∈ <0,1>, the ratio of those inside a unit circle
// should approach π / 4. Therefore, the value of π
// should be:
yield ratio * 4;

Iterable<Point> generateRandom([int seed]) sync* {
final random = new Random(seed);
while (true) {
yield new Point(random.nextDouble(), random.nextDouble());

class Point {
final double x, y;
const Point(this.x, this.y);
bool get isInsideUnitCircle => x * x + y * y <= 1;

Get started with Dart
TypeScript is a superset of JavaScript; a valid JavaScript program is also valid TypeScript but adding static typing. The compiler can also work as a transpiler from ES2015+ to current implementations, so you always get the latest features.
Unlike many other languages, TypeScript keeps the spirit of JavaScript intact, only adding features to improve the soundness of the code. These are type annotations and other type-related functionality that makes writing JavaScript more pleasant, thanks to the enabling of specialized tools like static analyzers and other tools to aid in the refactoring process. Also, the addition of types improve the interfaces between the different components of your applications.
Type inference is supported, so you don’t have to write all the types from the beginning. You can write quick solutions, and then add all the types to get confident about your code.
TypeScript also has support for advanced types, like intersection types, union types, type aliases, discriminated unions and type guards. You can check out all these in the Advanced Types page in the TypeScript Documentation site.
JSX is also supported by adding the React typings if you use React.
class Person {
private name: string;
private age: number;
private salary: number;

constructor(name: string, age: number, salary: number) { = name;
this.age = age;
this.salary = salary;

toString(): string {
return `${} (${this.age}) (${this.salary})`;

Get started with TypeScript
Elm is a purely functional programming language that compiles to JS, HTML, and CSS. You can build a complete site with just Elm, making it a great alternative to JavaScript frameworks like React. The applications that you build with it automatically use a virtual DOM library, making it very fast. One big plus is the built-in architecture that makes you forget about data-flow and focus on data declaration and logic instead.
In Elm, all functions are pure, which means that they will always return the same output for a given input. They can’t do anything else unless you specify it. For example, to access a remote API you would create command functions to communicate with the external world, and subscriptions to listen for responses. Another point for purity is that values are immutable; when you need something, you create new values, instead of modifying them.*
The adoption of Elm can be gradual; it is possible to communicate with JavaScript and other libraries using ports. Although Elm hasn’t reached version 1 yet, it is being used for complex and large applications, making it a feasible solution for complex applications.
One of the most attractive features of Elm is the beginner-friendly compiler, which, instead of producing hard-to-read messages, generates code that helps you to fix your code. If you are learning the language, the compiler itself can be of big help.
Continue reading %10 Languages That Compile to JavaScript%


JavaScript Design Patterns: The Observer Pattern

In JavaScript, there is a problem that comes up often. You need a way to update parts of a page in response to certain events, with the data these provide. Say, for example, user input that you then project into one or many components. This leads into a lot of push-and-pull in the code to keep everything in sync.
This is where the observer design pattern can help — it enables one-to-many data binding between elements. This one-way data binding can be event driven. With this pattern, you can build reusable code that solves for your specific needs.
In this article, I’d like to explore the observer design pattern. It will help you solve a common problem you see in client-side scripting. That is one-to-many, one-way, and event-driven data binding. It is a problem that comes up often when you have many elements that must be in sync.
I’ll use ECMAScript 6 to illustrate the pattern. Yes, there will be classes, arrow functions, and constants. Feel free to explore these topics on your own if you are not already familiar. I’ll use parts of ES6 that introduce syntactic sugar only, so it is portable with ES5 if need be.
And I’ll use Test-Driven-Development (TDD) to work on the pattern. This way you have a way knowing how each component is useful.
The new language features in ES6 make for some succinct code. So, let’s get started.
The Event Observer
A high-level view of the pattern looks like this:

├── subscribe: adds new observable events

├── unsubscribe: removes observable events
└── broadcast: executes all events with bound data

After I flesh out the observer pattern I’ll add a word count that uses it. The word count component will take this observer and bring it all together.
To initialize the EventObserver do:
class EventObserver {
constructor() {
this.observers = [];

Start with an empty list of observed events, and do this for every new instance. From now on, let’s add more methods inside EventObserver to flesh out the design pattern.
The Subscribe Method
To add new events do:
subscribe(fn) {

Grab the list of observed events and push a new item to the array. The list of events is a list of callback functions.
One way to test this method in plain JavaScript is as follows:
// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act

// Assert
assert.strictEqual(observer.observers.length, 1);

I use Node assertions to test this component in Node. The exact same assertions exist as Chai assertions too.
Note the list of observed events consists of humble callbacks. We then check the length of the list and assert that the callback is on the list.
The Unsubscribe Method
To remove events do:
unsubscribe(fn) {
this.observers = this.observers.filter((subscriber) => subscriber !== fn);

Continue reading %JavaScript Design Patterns: The Observer Pattern%


Instant Form Validation Using JavaScript

HTML5 introduces a couple of new attributes for implementing browser-based form validation. The pattern attribute is a regular-expression that defines the range of valid inputs for textarea elements and most types of input. The required attribute specifies whether a field is required. For legacy browsers that don’t implement these attributes, we can use their values as the basis of a polyfill. We can also use them to provide a more interesting enhancement – instant form validation.
We have to be very careful here not to get carried away, creating overly aggressive validation that breaks the natural browsing behavior and gets in people’s way. For example, I’ve seen forms where it’s impossible to Tab away from an invalid field – JavaScript is used (or rather abused) to force the focus to stay inside the field until it’s valid. This is very poor usability, and directly contravenes accessibility guidelines.
What we’re going to do in this article is far less intrusive. It’s not even full client-side validation – it’s just a subtle usability enhancement, implemented in an accessible way, which (as I discovered while testing the script) is almost identical to something that Firefox now does natively!
The Basic Concept
In recent versions of Firefox, if a required field is empty or its value doesn’t match the pattern then the field will show a red outline, as illustrated by the following figure.

This doesn’t happen straight away of course. If it did, then every required field would have that outline by default. Instead, these outlines are only shown after you’ve interacted with the field, which is basically (though not precisely) analogous to the onchange event.
So that’s what we’re going to do, using onchange as the triggering event. As an alternative, we could use the oninput event, which fires as soon as any value is typed or pasted into the field. But this is really too instant, as it could easily be triggered on and off many types in rapid succession while typing, creating a flashing effect which would be annoying or impossibly distracting for some users. And, in any case, oninput doesn’t fire from programmatic input, which onchange does, and we might need that to handle things like auto-complete from third-party add-ons.
Defining the HTML and CSS
So let’s have a look at our implementation, starting with the HTML it’s based on: