Pigs in namespaaaace

When you’re working on a JavaScript (JS) app you’ll create loads of functions and variables. By default in JS, there is no namespacing so everything you declare is effectively in the global namespace. This can lead to issues where two or more functions or variables can easily be called the same thing and create conflicts. Take this example:

function pigs() {
  console.log("Pigs in space");
}

function pigsDance() {
  console.log("Pigs dancing in space");
}

function pigs() {
  console.log("Pigs in Mexico");
}

pigs();

The output of this will be “Pigs in Mexico”. To avoid collisions like this we can use an object to create a namespace. So reworking our above example:

var space(){
  function pigs() {
    console.log("Pigs in space");
  }
  function pigsDance() {
    console.log("Pigs dancing in space");
  }
}

function pigs() {
  console.log("Pigs in Mexico");
}

space.pigs();

This will return “Pigs in space”. By creating the object and making “pigs()” and “pigsDancing()” properties of that object, we isolate them from the global namespace that “pigs()” lives in.

This way, when we need our pigs in space, that’s exactly where they will be.

Atom snippets

One of the things I love about modern text editors is code snippets. Coding tends to involve repetition, code snippets can really help cut down on needless typing.

I group all my code snippets by prefixing them with “my”. That way to view all my snippets I just start typing “my” and Atom shows all my snippets for the specific file type I’m currently working on.

Some simple examples I use quite often are:

myHTML – My own HTML boilerplate

<!DOCTYPE html>
  <html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <link rel="stylesheet" type="text/css" media="screen" href="assets/css/style.css" />
  </head>

  <body>
  
  <script type="text/javascript" src="assets/js/script.js" charset="utf-8"></script>
  </body>

  </html>

myjQuery – Inserts jQuery using their CDN

<script src="https://code.jquery.com/jquery-3.3.1.min.js"   integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="   crossorigin="anonymous"></script>

myFontAwesome – Inserts font awesome using their CDN

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

myLog – inserts a console.log() to help debug my JavaScript

console.log()

Getting all this working in Atom is a fairly easy affair. I found the below video by Hitesh Choudhary super useful.

Selection

One thing I notice about jQuery is how it simplifies common tasks. A good example is something you do all the time with JavaScript, select DOM elements. In JavaScript selecting all li elements would look something like this:

document.querySelectorAll( "li" );

The same selection using jQuery is like this:

$("li")

At this stage of my learning, I can’t say I see the above as a major advantage. Yes, it’s shorter but you could argue it’s also less descriptive for the reader. Brevity isn’t always a net win in code. This is especially true when tools like Emmet and other text editor tricks auto-complete a lot of code. So it’s not 100% clear to me what the advantage is.

It will be interesting as my jQuery knowledge grows if my feelings toward it change. At this early stage, I can’t help feeling sceptical. Especially when I keep hearing about frameworks like Angular and React. I guess we will see.

Emmet!

Whatever your text editor of choice (I just can’t quit you Atom) there is a wide range of plugins to enhance its capabilities. One such plugin that I use constantly is Emmet.

Emmet can be used for a number of things, but where it really shines is speeding up my HTML production. Emmet uses a CSS like syntax to quickly produce common HTML code.

The most common situations I find myself using it is when I initially create an HTML document. To do this you just type “!” and hit tab. The result will be:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>

</body>

</html>

Perhaps most useful of all is adding repetitive blocks of HTML like lists. Just type “ul>li.lego{Awesome}*10” then hit tab and you’ll get:

<ul>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
  <li class="lego">Awesome</li>
</ul>

Or you can get super fancy and nest all sorts of things. Give something like this a go. Type “div.awesome>(header>ul>li.item$*5>a{Awesome thing $})+footer>p{Awesome}” and hit tab. Boom you get:

<div class="awesome">
  <header>
    <ul>
      <li class="item1"><a href="">Awesome thing 1</a></li>
      <li class="item2"><a href="">Awesome thing 2</a></li>
      <li class="item3"><a href="">Awesome thing 3</a></li>
      <li class="item4"><a href="">Awesome thing 4</a></li>
      <li class="item5"><a href="">Awesome thing 5</a></li>
    </ul>
  </header>
  <footer>
    <p>Awesome</p>
  </footer>
</div>

As you can see, once you learn the basic structure, everything is awesome with Emmet.

jQuery

What is jQuery?

jQuery is a JavaScript library designed to simplify front end web development. It is the most widely deployed JavaScript library by an insanely large margin.

Why use jQuery

There are quite a few reasons you’d want to use jQuery, or a library like it, in your project rather than vanilla JavaScript. Here are a few examples.

Ease of use

JavaScript can be a handful, jQuery can be far cleaner and more concise than the equivalent in vanilla JavaScript. Take a look at these two examples of a fade in effect:

JavaScript Fade In

function fadeIn(element) {
  element.style.opacity = 0;
  var last = +new Date();
  var tick = function() {
    element.style.opacity = +element.style.opacity + (new Date() - last) / 400;     
    last = +new Date();
    if (+element.style.opacity < 1) {
      (window.requestAnimationFrame && 
      requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }   
  };
  tick();
}
fadeIn(element);

jQuery Fade In

$(element).fadeIn();

Cross browser support

Cross-browser support is one of the most difficult things about web development. jQuery normalises this so you don’t have to worry about different browsers as much.

This reason becomes less true with time. However, If you need to support older browsers, particularly anything older than IE8 then you should seriously consider jQuery.

Lots of people use jQuery

It might seem like a silly reason to use something just because loads of others are using it too. Having said that there are some real benefits to that thinking. In particular, there are plenty of resources available to help you learn and use jQuery. So if you need examples of how to do something you should have no problem finding them.

Even if you’re already a skilled developer, the practice of coding is continuous learning. So it’s always good to have a strong community around the area in which you work.

Why not use jQuery?

Based on the above you’d think jQuery would be a no brainer, and in many situations that’s true. However there are plenty of situations where it isn’t the best option, here’s why.

You can do everything without it

There is nothing in jQuery you can’t do in vanilla JavaScript. So depending on your project adding jQuery to the mix may actually be creating an unnecessary dependency. If you’re not using many of jQuery’s capabilities in your app, it pay’s to consider alternatives.

jQuery contains hundreds of methods that on many applications you’ll never use. There’s no sense in bundling all that in if you’re only using a small part of it.

People are moving away from jQuery

This one is a little contentious as depending on who you’re talking to. For a few years now there are signs that people may or may not be moving away from jQuery. Regardless, if new jQuery based projects are in decline there is such a huge existing usage of the library it still pays to learn it.

We’ve all got issues

Since I’ve been learning JavaScript I’ve been making an effort to do things as if I was working with others. The idea being that any project of meaning is very likely a collaborative one.

To my mind understanding how to effectively work with others on a coding project is as important as the coding itself. Also understanding how people work is always good when managing people is part of your professional life.

To that end, since I’ve recently created an “app” and put it on GitHub, the obvious next step was to record any issues with the app. So far there are three, but I suspect there are plenty more.

  1. The interface needs styling
  2. What constitutes victory isn’t clear
  3. Max score change doesn’t affect victory formatting

Over time I aim to chip away at these and any other reported issues. Of course being open-source, it’s entirely possible others may do the same. Which would no doubt teach me something too…

I made a thing – Score keeper

I’ve been doing a web development course for a few months and today I made my first thing that actually does something. Nothing amazing mind you, but it’s a start.

Do you ever have the need to keep score in a best 2 out of 3 kind of way? Me neither, but here’s a web app that does it regardless  🙂

At some stage, I’ll pop it on a web server and make it live for anyone to use. For now, if you’re interested in the code, take a look at the GitHub repo or you can download it directly.

Update: The app’s now live. Give it a try.

Listen to your heart

JavaScript is responsible for the behaviour of your website/app. At the heart of affecting the behaviour of the page is listening for user interaction events. These are things like button clicks, key presses and drags and drops.

To do this, first we select an element then we add an event listener. To add an event listener we use the “addEventListener” function like this:

var button = document.querySelector( "button" );

button.addEventListener( "click", function() {
  console.log( "SOMEONE PLAY SOME ROXETTE!" );
} );

A common pattern is to add event listeners to a set of elements, like each item in a list so each item is clickable. The code for this would look like this:

var listItems = document.querySelectorAll( "li" );
for ( var i = 0; i < listItems.length; i++ ) {
    listItems[ i ].addEventListener( "click", function () {
        this.style.color = "pink";
    } );
}

You can also add multiple event listeners to the same element. So, for example, you can listen for a hover and a click on the same button and take separate actions for each. Listen events are very powerful and a great addition to your JavaScript coding toolbelt.

DOM DOM DOM

Playing with the DOM is all about adding interactivity to your page. The DOM (Document Object Model) is the interface between your JavaScript and your HTML+CSS. The browser takes all the elements of your page and turns it into a JavaScript object.

All the elements of the DOM for your page are contained in the object “document”. You can show everything in “document” by using this command in your browser’s console:

console.dir(document);

Working with the DOM is similar to CSS. This is because you select an element then you manipulate it. Here’s an example of what I mean:

var batmanComments = document.querySelectorAll( ".batmanComments" );

In the above example, we are selecting all elements with the class “batmanComments”. Now to do something with our newly selected elements:

var length = batmanComments.length;
for (var i = 0; i < length; i++) {
    batmanComments[i].textContent = “Ironman sucks”
}

This code replaces the contents of each element in the “batmanComments” array with the string “Ironman sucks”… because maturity isn’t Batman’s strength.

If you want more details on working with the DOM, MDN is a good place to start and an even better reference as you’re learning.

GitHub flow

I’ve recently been attempting to contribute to some open-source GitHub projects with varying degrees of success. One thing that’s extremely useful to do before you start contributing is to develop a basic understanding of the standard GitHub workflow.

It’s not especially complicated but it can be a real faff if you don’t do it correctly from the start.

Step 1 – Clone the repo

The first thing you’re going to need is your own copy of the project to work on. You do this by cloning the repo to your local machine where you’ll make your changes.

Step 2 – Create a branch

Now you’ve got a local copy you’ll want to create a separate branch for your specific contribution. For example, if you’re working on issue #3271 and issue #3244 you’ll want to create separate branches for each issue. It’s a good idea to name this something like fix/issue#3271 and fix/issue#3244 so you know which branch to submit for what issue once you’re done.

Step 3 – Make commits

Once you’ve made your changes within the appropriate branches make your commits. Commits tell the story of your changes, be sure to write clear concise comments that communicate your intent to other developers reading them.

Step 4 – Submit a pull request

Once you believe you’ve completed your changes create a pull request to submit them. Create one pull request for each issue and corresponding branch you’ve created. Pull request are a way of notifying the projects “owner” of your proposed changes for consideration.

Step 5 – Discuss and refine

It’s likely upon review there will be some conversation around the code and changes. Others may have ideas on different approaches and/or improvements to the update. You can continue to make changes and improvements to refine your solution as a result of these discussions. Just keep making those commits.

Step 6 – Deploy

This part you’re likely to be less involved with. If and when the “owner” decides to use your code they will likely deploy it into the master branch where it will then be tested along with all the other changes made in that round of updates. This is were things get exciting.

Step 7 – Release

Assuming everything is tickety-boo your code is then included in the next production release leaving you with a sense of satisfaction from having helped to make the world a better place one pull request at a time. Don’t forget to be grateful for all the help along the way. Open-source is all about community coming together, so remember to give high fives all around.