Different Conditional Syntaxes in JavaScript

There are a few ways of using conditionals in JavaScript. I’ve started thinking about it again as I’ve just discovered another new way.

Lets start off with some basic set up stuff for our examples – a variable, which can be true or false and functions to use in either case:

var isAllowed = false;

function admit() {
  console.log("admitted");
}

function reject() {
  console.log("rejected");
}

The first way I learned to write a conditional, which I consider the classic way, is with if and else clauses like this:

if (isAllowed) {
  admit();
} else {
  reject();
}

If you don’t need the else part, you can do it in one line, leaving out the curly braces like this:

if (isAllowed) admit();

Another way of writing it is to use a ternary operator. The first part before the question mark is evaluated. If it’s true the next part between the question mark and colon is used; if false the last part after the colon is used:

isAllowed ? admit() : reject();

If you want this style of expression, without actually writing “if” but you don’t want the else part there is yet another way.

Look at this:

!isAllowed || admit();

Weird, eh? With an OR expression using ||, the first part is evaluated or run if a function. If true it stops there. If false it evaluates or runs the second part. In case you’re new to this, the ! means NOT or inverts the meaning. So, we’re saying if isAllowed is false, stop; otherwise run the admit() function.

It’s the same technique often used to set default values, just turned around:

var carModel = getCarModel() || 'unknown';

If you’re free to use any of these I’d probably advise sticking to the classic if (else) with the braces. It’s so much more readable and can be understood by a developer at any level. I like the last technique but I’d only use it in solo projects or where I can’t use anything else.

Learning the Right Things

With so much happening so fast knowing what new tech to learn next can be difficult. Where should you invest your time and energy? What if you spend ages learning the shiny new framework and it’s gone within 2 years?

There are a lot of trends and a lot of new-fangled things do come and go. How do you spot the ones that are going to stick around. It’s not easy – you kind of have to go with the flow, not swim against the tide (2 water based metaphors in one sentence, tut).

In front end development there are currently a few big JavaScript frameworks – Angular, React and Vue. It seems obvious to me that none of these are going away any time soon. Which do you choose? It really doesn’t matter. Learning one in depth, finding its powers and limitations, will help you learn the others or other future technologies.

If you’re really not sure where to turn I’d focus on core learning. In the front-end world, learn plain JavaScript. With ES2015 and newer versions than that emerging there’s still plenty to take on and perfect. That knowledge will always be useful.

I guess my short answer would be to favour the evergreen HTML, CSS and JavaScript over associated tech like Pug, Sass, TypeScript, etc. As the core technologies get better over time these current convenience technologies may one day not be needed.

One word answer. JavaScript. :)

Developing in Codepen

A look at why and how I use Codepen for front end development work.

Background

I work on a web app with a development team. We use AngularJS with a RESTful API. My role is looking at the design and UX side of things and scoping out how a new feature will look and behave in a web browser, or, I should say, in various browsers at different screen sizes.

I generally do my work up front. I’ve always been a design in HTML and CSS kind of guy. To me, with my skill set, working in a graphics editor takes as long as coding it so it makes little sense for me to do the work twice.

Until recently, I’ve been using static HTML and then another developer has added the binding and data. Where the feature is on a new screen I can go a step further and create a dummy data object, to represent the data returned from the API, and actually do the binding as well as create any custom behaviour.

Working on existing screens has been much more difficult. It’s almost impossible to add new data, binding and behaviours without breaking the existing code. To use a dummy data object I need to intercept the real data retrieval and replace the object, which stops the page working when wired up again. However I work things, I’m having to check in code which is not releasable.

A new way of working

I’ve started using Codepen to abstract away the new feature. I set up a new pen, import any existing dependencies and then create the HTML, CSS and JavaScript for the new feature in isolation.

This means that the original project code does not get touched and broken. As the next developer brings in any model/schema changes he/she can bring in my front end code so we don’t have any breaking check-ins.

By importing the dependencies – JavaScript libraries, CSS – we avoid any clashes or inheritance issues and additional work trying to integrate my code.

It also means I can give the new feature my full attention without having to use other parts of the screen, for example, if I’m working on a modal window, I don’t have to go through the usual page processes in order to call it.

I’m using Codepen in the way it was intended, as a front end playground, an environment where I can experiment with different ways of doing things. The results are displayed in a frame, updated instantly as you type, which makes working much faster – no more manual refreshing or rebuilding.

From what I’ve described up to this point, this abstraction could be done by making a copy of the page but copying the HTML page, the CSS and JavaScript and changing all of the references between these files is quite a headache. Believe me, I’ve been there enough times.

One of the massive advantages of Codepen for a designer is the ability to fork pens, so you just hit one button and you’ve got an exact copy of the pen you were working in, making it very easy to create a few variations of a design.

As each pen is available on a public URL it’s easy to share designs with colleagues or clients and they can see a working prototype – much better than a static screenshot. It also means that links can be embedded in documentation. Personally, I feel that now web animation has become mainstream, it’s important to be able to show how screen elements transition between states, how things appear/disappear and demonstrate where the user’s attention is drawn through processes. Static screenshots just don’t cut it any more.

Final point. Designing in the browser with work stored in the cloud is awesome for design. I could be out and about and suddenly see some inspiration for something I’m working on or get a new idea. Rather than hope I’ll remember it, I can quickly create a new pen or fork an existing one and add some code or notes there and then from a phone or tablet. I don’t have to hope I’ll remember or wait until I’m back at my desktop. It’s exactly what the web should be.

What I Learned in 2014: Part 2 – Javascript and Google Maps

This is the second part of a three-part article looking back at what new web things I’ve learned in 2014. This part focuses on JavaScript.

JavaScript and jQuery

This is a big area, probably the area where I have made the most progress in the last year. The main shift for me has been from doing everything in jQuery, which I learned first, to using native JavaScript. Hopefully by learning to do more with native Javascript I can cut down on the jQuery bloat, especially in mobile friendly pages.

In “vanilla JavaScript” I’ve learnt to use a few new built-in functions, which perform very well in modern browsers. One of the things that really slows down a page’s performance in JavaScript is looping through a long list of items and performing various operations within each. I’ve learned four new functions which perform operations very quickly – map, filter, forEach and reduce. I would urge anyone using standard for loops to look into these. One for loop operation I tried on a list of 10,000 items killed Chrome. Switching to using map it worked in under a second. I believe that jQuery’s each and filter functions already leverage these bult-in functions. The other useful thing I’ve discovered when working with loops is to move anything you can outside of the loop, e.g. a function. Don’t declare it every time – just do it once and call it each time.

I’ve finally got the hang of the ternary operator. This just means that I can now write my conditional statements in a much more compact way, things like return (confirmed) ? true : false;. If the variable ‘confirmed’ is truthy, return true, otherwise return false.

A great discovery in the last couple of months has been the hashchange event. The browser can detect changes to the part of the URL that appears after the #. This means that when we use links to change something like filter the data in a table, instead of the link’s href bring empty or set to the meaningless “#”, we can put something meaningful in there. For example our href could be “#female” and the URL will change to reflect this. The hashchange event will listen for this change and we can then grab the part after the hash symbol using window.location.hash and do our filtering. This has the added bonus of appearing in the browser’s history so the user can hit their back button to undo a filter. Much better and feels like this is how it’s supposed to work.

I think I’ve now understood how to properly use functions and objects in JavaScript to set the appropriate scope for variables. Wrapping functionality in functions means that each function is its own self-contained unit, which means no unexpected or conflicting references cropping up and it makes the code easier to maintain and test.

Earlier this year I wrote a jQuery script to handle pagination in a HTML table. I won’t go into the horribly complicated detail here but the learning point for me was to get the logic clear in my mind before getting into the code. I actually went back to pen and paper, sketching out the various scenarios and then finding the patterns to create my code.

JavaScript Frameworks and jQuery Plugins
Thanks to a very patient colleague I’ve now got a much better grip on Angular.js. I can now work with not just binding data in the HTML but can also write directives to create new page components and services to handle commonly required functions.

As part of the Angular work I’ve also learned how to do Unit Testing using the Jasmine framework. Unit testing always felt like a lot of extra work to me but now I see that having a long list of small tests that run is invaluable. It gives you the freedom to write new code knowing that any knock-on effects you create in the process will be picked up. It makes for far more robust and less buggy code.

Recently, I’ve implemented 2 jQuery plugins into a project, tablesorter for automatically sorting the rows of a table by clicking on a column heading, and elevateZoom for adding the capability of zooming in on a thumbnail image, like we often see on clothing details pages. Both are very well written with a lot of options available. Using these has made me realise that I can now go into the code of the plugins and actually follow (more or less) what is going on. I hope to be able to write and share some of my own in the next couple of years.

Google Maps API v.3

I’ve now spent a few months working with this API and have got a good understanding of how it works and how it can be used and extended to do more. I created my own utility library of functions for all the things I need to do regularly – draw markers and polygons with info windows which appear on click, calculating areas, converting area units, adding data layers and heatmaps, encoding/decoding polygon paths, adding new map controls, etc. There was also some more advanced functionality in there too which goes beyond what’s included in the API – calculating the optimal bounds (map viewport) to show a number of polygons, determining the direction or winding (clockwise or anti/counter-clockwise) of a polygon, calculating the centroid (centre from the average coordinates of points) of a polygon.

I’ve also used some third party features to extend the mapping functionality. One of these has allowed me to cluster markers so rather than have a lot of marekrs close together on screen we show a number of markers, much neater. Another has enabled me to place text labels on the map, which isn’t possible out-of-the-box.

The key tricks that I have picked up along the way are to 1) push any markers or polygons into an array so you can access them easily in JavaScript and 2) add your own custom properties to the native objects for markers and polygons, e.g. id or name, so that you can identify them easily in code.

Introducing… Dinowebs.net

DinowebsAs a web developer and programmer I’m always on the look out for solutions to little problems. How do I do that? How can I make that do this without X, Y and Z happening? You get the idea.

My first port of call is always Google. The way I see it is that I’m unikely to ever have a technical requirement that somebody else hasn’t had before. In fact, it’s highly likely that hundreds, even thousands of people have faced the same challenges. By using the right search terms on Google I can usually find the answers to my problems. This inspired me to build a technical blog. It’s my way of sharing what I’ve learnt and, hopefully, helping someone else out.

As well as trying to help others it’s also tremendously useful to me. Every time I overcome an obstacle I write about it and provide the solution giving code examples where I can. It’s very handy to just be able to just come back to it rather than try to remember things that I’ve done in the past. I also use the site for setting up links to resources I like and use. Again, it just saves me time looking for things.

My site is called Dinowebs, http://dinowebs.net. The site covers all sorts of coding and web development subject matter. Please take a look.