How To Add Feature Flags Into Your Javascript Applications

Feature flags are a great way to prevent stale branches by regularly shipping features in your code without officially enabling them. A feature flag let’s you turn code on and off, in the case of features, a feature flag means you can regularly merge branches and release them.

While there are many different ways you can approach this, one of my favourite and most simple approaches is a features.json file in your application.

It can be something as simple as a JSON file of properties and boolean values.

{
    "feature1": true,
	"feature2": false
}

Or in the case of something more flexible and less straightforward it can be something like this where we can specify specific roles who are allowed to use a certain feature.

{
    "feature1": {
        "roles:" ["admin", "editor"]
        "enabled": true
    },
    "feature2": {
        "enabled": false
    }
}

In your code, you import the features.json file and then reference the features. Depending on your framework or environment, this will look different.

import features from './features.json';

const FeatureOne = features.feature1 ? import ('./features/feature-one') : null;

If you were to do this in a framework like Angular or Aurelia, you would create a service or middleware of some kind which compares the route against the property in your features file and reacts accordingly.

import features from './features.json';

export class FeatureService {
    getFeature(key) {
        return features?.[key] ?? null;
    }
}

There are a few feature flag services out there which provide SDK’s and ways to turn features on and off, do A/B testing, but for most use-cases, you don’t need anything else other than a JSON file and a little code to wire it all up.

How To Get Last 4 Digits of A Credit Card Number in Javascript

Recently whilst working on my Aurelia 2 book, for the example application where you checkout I needed to add in the ability to provide a card number and when it saves, the last 4 digits of the card number get saved.

This is one of those things that as developers we won’t do too often, but it’s easy using substr to trim a text string to a certain length.

let ccNumber = '4560265043620583';
let lastFourDigits = ccNumber.substr(-4);

By providing -4 as the value to substr you’re telling it to take the last 4 characters from the string. The result from our example will be 0583. You can also provide non-negative numbers to go from the beginning as well.

I am sure there are other ways of doing the same thing, but I always look for the easiest to read and easiest to understand solutions and substr fits the bill nicely.

I Used To Hate Using Reduce In Javascript, And Now I Can’t Stop

I used to be vehemently against using `reduce` in Javascript. It wasn’t because I thought there was a better way, I actually think the functional programming purists and their aggressive approach to advocacy are what really turned me off. That and those who advocate for using it over a basic for loop as well.

Now, there are instances where I truly believe that filter, map and reduce should not be used. If you’re just wanting to quickly iterate over a collection of values, in many instances. a for..loop will beat all of those aforementioned methods in performance every single time. And if you’re dealing with large collections of items, you will notice.

The reduce method is great for reducing values to either a singular value or manipulating the shape of data from one form to another. If you want to flatten an array, look no further than reduce. Want to average out a bunch of numbers and return a singular value? Oh, hi there reduce.

Here is an actual snippet of code I wrote not long before writing this post:

return rows.reduce((arr, row) => {
    row.contractPayload = JSON.parse(row.contractPayload) ?? {};
    arr.push(row);
    return arr;
}, [])

I am taking a bunch of rows from an SQLlite database, iterating over them and parsing a property which is stringified JSON, parsing it into an object or empty object if it doesn’t parse properly.

If I was one of those fancy developers that used shorthand for everything, I could have used the spread operator to really condense this code down into a one liner (inside the callback), but I am far too practical and prefer writing readable verbose code in most situations.

For a long time I used to be the type of developer who would create a variable with an empty array inside of it and use a for loop to push into the array, which gives you the same result.

I instinctively find that I naturally will reach for reduce over a traditional for loop whenever possible. In instances where I notice substantial performance issues, I’ll write a loop.

The real power and value of reduce is that it negates the need for unnecessary code. I guess they call it reduce because it reduces the amount of code you need to write as well. Neat.

How To Develop A Seedable Dice Roll/Number Guess In JavaScript

Recently whilst working on some blockchain specific code, I needed to write a random number generator to simulate generating a range of numbers, except it needed to be predictable. The same input values produce the same output when provided.

In my case, I used values from immutable blockchain data such as the blockchain number, reference block number and transaction ID. I then allow the user to provide a client seed and generate a unique server seed on each roll as well.

For this, we will use the tried and tested and ever-versatile Seedrandom library by David Bau. It provides a wide variety of different algorithms for producing random numbers.

In this post, we won’t do anything outside of the norm. We will just use the default algorithm which for most purposes does what you would expect it to do.

For this example, we are going to assume the random number generator lives on the server in a Node.js environment. This would also work in a browser, but when generating numbers for a game or any serious application, you would never do it server side.

Firstly, make sure you install the seedrandom package by running: npm install seedrandom

const seedrandom = require("seedrandom");

const rng = (seed1, seed2) => {
  const random = seedrandom(`${seed1}${seed2}`).double();
  const randomRoll = Math.floor(random * 100) + 1;

  return randomRoll;
};

The seedrandom method accepts a seed string. This value produces a deterministic result, meaning if our rng function above is provided the same values for seed1 and seed2, the result is the same.

We then use Math.floor to take our random number and multiply it by 100 (the largest number we want to allow) and plussing it by one means the number starts at 1 instead of 0. This will produce a number between 1 and 100. You can change these values to suit.

For example, if you wanted to generate a number between 1 and 2 (for some kind of seedable coin flip) you would do something like this:

const randomRoll = Math.floor(random * 2) + 1;
const headsOrTails = randomRoll === 1 ? 'heads' : 'tails';

You can make your seed as long as you like. I highly suggest allowing the user to provide their own client seed as well as randomly generating a client seed which you reveal to the user after the fact.

With all of these values, users should be able to produce the same result independent of your site, this results in a provably fair algorithm for producing numbers.

A working code sample of what we did above can be found here on Codesandbox.

How To Get The Hash of A File In Node.js

Whilst doing some work in a library I maintain, I needed to add in the ability to calculate the hash of an included file for an integrity check feature I was adding in. The resulting solution is simple and not really boast-worthy, but given others might encounter a situation where they need a hash of a file, this might help.

const crypto = require('crypto');
const fs = require('fs');

const fileBuffer = fs.readFileSync('myfile.js');
const hashSum = crypto.createHash('sha256');
hashSum.update(fileBuffer);

const hex = hashSum.digest('hex');

console.log(hex);

For the createHash method you can supply different supported algorithms including; md5, sha1 and sha256. To the digest method, you can supply hex or base64. If speed is important to you, sha1 and base64 are the two fastest options in most cases, however, all options are fairly fast anyway.

Preferring If Statements over Ternary Operators In Javascript

Every so often thought-pieces will go around proclaiming that you are writing code the wrong way and that you should be writing your code this way instead.

One such opinion I have seen (and will not link because this isn’t a takedown) is recommending the use of Ternary Operators in Javascript over if statements.

While ternaries can make your code look cleaner in some cases by replacing multi-line if statements with one-liners, there are instances where they fall apart quite quickly. Ternary operators exist in all programming languages and the problems they can introduce into a codebase are universal.

Ternaries are hard to read

Sure, they might look cleaner, but ternaries can needlessly make code hard to read. This is the problem I have with “clever coding” and some developers pursuit to write the most convoluted code in an attempt to condense things.

const canAccess = user.isAdmin || user.isEditor || user.level > 6 ? true : false;

It’s a simple one-liner, but there is a lot going on here. Replaced with an if statement, things get a little easier to read.

let canAccess = false;

if (user.isAdmin || user.isEditor || user.level > 6) {
    canAccess = true;
}

Understandably, this is an exaggerated example and even so, there is room for improvement here. But, my eyes are instantly drawn to the if statement, it is easier to read and if I need to change it, it will be easier to change as well.

Ternaries fail at dealing with complex conditions

The above example is quite a simple set of conditional checks, but what happens in a situation where things are more complex? A good example is detecting keycodes on the keydown event in Javascript and reacting accordingly.

While in simple use-cases it is more than fine to use a ternary, complex scenarios with multiple conditions should be avoided like the plague. If you need to check multiple values or check multiple expressions, a ternary condition will be a nightmare.

const prevNext = (e.keyCode == 38) ? 'prev' : (e.keyCode == 40) : 'next' : null;

This is a relatively tame example of multiple expressions, can you imagine throwing more into the mix?

Ternaries are hard to debug

If you have a one-line ternary expression in your application, good luck setting a precise breakpoint. This is where the differences between a ternary statement and if statement is truly highlighted. Sure, you could use a console.log if you wanted to debug, but setting a breakpoint is not going to be possible.

Code that is broken up into multiple lines might not look as appealing as a condensed ternary condition, but at least you can set a breakpoint and go through it line-by-line to debug the flow.

I am not saying that you shouldn’t use ternaries, because they have a purpose. But to go as far as recommending their use over if statements in general defies all common sense.

Select Change Event Not Firing When Using Characters On Keyboard

Here is a nice bug-not-bug to close out in 2019. One of my Trello cards detailed what sounded like an error:

When toggling between two options (yes and no) in a dropdown, entering “y” changes to yes and quickly entering “n” does not switch to no. However, waiting a second you can change between them.

Some initial debugging suggested this was not actually a bug in our application. But, I knew if I was going to get the ticket closed off as not a bug, I had to have an explanation.

It turns out that browsers (well at least in Chrome and Firefox) select dropdowns are searchable by offering a delay allowing you to type in long values. The way I highlighted this was creating a dropdown with four options:

  • Yes
  • No
  • YNo
  • NYes

To highlight the error I created a JSFiddle demo here. The first dropdown contains the above options. Try pressing “Y” and then “N” quickly after, the selected value will then be “YNo” highlighting the searchability. Similarly, entering “N” followed by “Y” will yield “NYes” selected.

There is also a second dropdown with some years from 1988 to 1993 in the above linked JSFiddle demo. Try selecting the dropdown and then entering 1993 (which is the last option) you will see the searching feature in the browser selects 1993.

So, not a bug, just a browser feature. Admittedly, I didn’t actually know you could search values in a dropdown this way. I usually use my mouse to select values in a dropdown. We have some people on our team who shun the mouse and navigate through our main app using their keyboard.

Learn Javascript First

The front-end space over the last six years or so has really heated up, you could say superheated. As browsers become more powerful, devices continually improved and innovation a constant thing, no language is more popular and widely used than Javascript.

And yet, as learning resources have become more easily accessible and coding boot camps have become a thing, newcomers are being taught to lean on frameworks and libraries straight out of the gate.

This puts some newcomers into an interesting situation. They might have a good grasp of React or Vue, but lack basic fundamental knowledge of the language itself. It is all well and good to rely on a library, but the moment it can’t do something you want to do, you’re stuck.

While React and Vue might seem like safe bets, I can assure you that people said the same things about Knockout, ExtJS, AngularJS, jQuery and a whole list of other frameworks and libraries that have come and gone over the years.

People will tell you things are different these days, maybe they are. But what happens when Hype.js becomes the popular option and you’re forced to learn a new library with limited Javascript knowledge? You get left behind, that’s what happens.

The only constant is Javascript

The common theme here amongst these rising and falling trends when it comes to technology on the front-end is Javascript. While WebAssembly has high hopes of shifting some responsibility from Javascript, it will remain the number one choice for client-side scripting.

As tempting as it might be to learn React Hooks or try Vue 3, the more you rely on a tool and use it as a language crutch, the further you’re falling behind. Learn Javascript and the rest comes naturally.

If you are an experienced developer, you should be learning new frameworks and libraries, leverage your knowledge of Javascript to widen your skillset and pad out your C.V. If you’re a junior who graduates college or a coding boot camp, learn the language first.

Are Classes in Javascript Bad?

Staunch functional proponents will fire up at the mere mention of classes or any form of object-oriented programming. These arguments go way back to before Javascript was even a thing or as popular as it is now.

Let’s clear the air and point out that classes in Javascript are not real classes. They’re often compared to the likes of Java and other languages that promote OOP-style programming, but classes in JS are unlike those implementations. Javascript has prototypes and prototypes are not classes.

When the ES2015 Javascript standard was released (its biggest update ever), a plethora of new and exciting features came with it. New syntax and API’s, in the mix, was classes (sugar over conventional prototypal inheritance). Perhaps the most controversial addition of them all.

Here is the one thing that class opponents forget: classes in Javascript are optional. They’re not being forced on developers, you either use them or you don’t use them. It is really that simple. And yet, the arguments and noise around their inclusion (especially 2015/2016) you would be forgiven for thinking they’re a requirement to program in Javascript.

Inheritance

One of the biggest downsides to object-oriented programming and classes is inheritance. I am a fan of OOP style programming and even I agree that inheritance can be a nightmare and paint you into a corner.

But here is a secret that functional programming proponents don’t want you to know: inheritance is optional.

I use classes in my Aurelia applications and I avoid inheritance whenever possible. If I do use inheritance (which sometimes I do) I will be strict about it and only have one level of inheritance (parent-child relationship). More than one level of inheritance is a recipe for a bad time. I also try and avoid super calls as well.

Not all uses of inheritance are bad, it can be useful when you want to avoid duplicating code between multiple classes. If you’re building a widget-based component UI and your components all share similar implementation details except for a few configuration-specific pieces of data, inheritance works well here.

In many cases, I use classes as structs for modelling specific pieces of data in my applications, for example:

export class UserModel {
    constructor(name, email) {
        this.name = name;
        this.email = email;
    }
}

I actually prefer the aesthetics of a class over a function. I also love how I have to use the new keyword to explicitly create a new instance of my UserModel.

But the argument that you shouldn’t use classes because it is easier to fall into certain traps is nonsense. Javascript is a language full of traps that extend beyond the likes of classes which are quite low on the scale of JS gotchas.

If you are also working with TypeScript, the benefits of classes are even better when you throw collections and generics into the mix. The development experience just makes sense. I let the TypeScript compiler decide if my classes should be transpiled to functions, prototypes or classes.

I’ve read quite a lot on the subject of OOP and the main argument always seems to boil down to inheritance, followed by personal preference.

Composition <> Inheritance

Whenever the classes vs functions debate arise, people take sides and stances on one side or the other. The truth is you should not and do not have to choose a side, you can use both.

You can still use classes where they make sense and in other parts, use functions where they make sense. Sometimes you just need simple functions and other times, you might like the semantics of a class for organising your code.

If you are implementing a feature/writing code and a function feels appropriate, write a function. If a class feels more appropriate, use a class instead.

Web Components

If you head over to the Google fundamentals for creating custom elements or Mozilla MDN in Web Components, surprise surprise you will find classes are what you use to author custom elements.

Sure, you could just directly write the prototype chain yourself, but it’s going to result in ugly code that is just painful to maintain. The sweet syrupy abstraction that classes provide here is immediately obvious from an aesthetics perspective.

I think classes make a lot of sense when creating custom elements. You’re extending the inbuilt element type and creating your own variant of it. One of the things that classes do well.

Frameworks + First-Class Citizens

Angular and Aurelia are two fully-featured front-end frameworks that have leveraged Javascript classes since the beginning in 2015. I have quite a few Aurelia applications in production, all leveraging classes, sprinkled with a function or two.

The rewrite of Angular (Angular 2+) also treats classes as a first-class citizen. While React might be the most popular option out there, in the enterprise and government sectors, Angular is the king. A lot of Australian government agency applications are built using Angular.

I have not seen or heard of any developer, agency or company running into any kind of problem as a result of classes being a requirement to build Aurelia or Angular applications. If you have, I would love to know.

In instances where classes cause problems, it is because the developer using them is to blame. A bad mechanic blames their tools.

Ignore The Noise, Form Your Own Opinions

I don’t pretend to have all of the answers or be the worlds greatest coder, but I know what works for me based on my years of experience. Be wary of anyone who argues there is only one right way to develop in Javascript because there isn’t.

There are quite a few prominent figures in the JS community who will vehemently argue against classes. They will tell you they have seen companies lose millions, go bankrupt and projects completely scrapped because of classes.

Most of the anti-class crowd have an agenda. You will discover the common thread amongst most anti-class dev-influencers is they’re selling training courses and other material. They will tell you there is only one way to do something and to signup for their “Right Way of Doing Things” course for developers.

One person’s right is another person’s wrong.

Getting Typescript 3.7 To Work With Webpack and ts-loader

At the time of writing this post, TypeScript 3.7 is in beta. Eventually, this post will become irrelevant. But, for the moment if you are trying to get TypeScript 3.7 Beta or any of the RC builds working with Webpack and ts-loader you might have encountered a bunch of red text in your console.

In my case, I had target: "esnext" set in my tsconfig.json file which the ts-loader plugin should read and set the appropriate settings. And yet, TypeScript 3.7 Beta was not working despite making sure everything was up to date.

It turns out at present, ts-loader does not seem to work with esnext as the target value (hopefully, this changes when TypeScript 3.7 is released). To get things working, all you need to do is change your target value in tsconfig.json to es2018 like this: "target": "es2018"

In my case, that fixed the issue and I could use the exciting new features TypeScript has to offer such as Nullish Coalescing and Optional Chaining. Happy days.