Categories
Dev JavaScript Projects Udemy

YelpCamp

I’ve now reached a turning point in my web dev course. This morning I started writing code on my first meaty project, YelpCamp.

As the name implies the YelpCamp project is Yelp but for campsites. The idea isn’t to release this as a service that people will actually use. The intent is to combine what I’ve learnt from the past few months and use these skills to make a cohesive project that could be released.

I’m quite excited to have finally reached this point. As much as I’ve enjoyed developing specific skills, the parts of the course I’ve enjoyed so far is the work with a visible output. I have a feeling YelpCamp will be a big learning experience and something I’ll likely look back on as a reference in any future developments I do. A library of learnings if you will.

As with other parts of the course I intend to share my progress and code here as a form of public note-taking. I’ll create a specific public GitHub repo so you can follow along and see how the code changes over time. I expect this part of the course will likely take me about 6-8 weeks and will make up the vast majority of posts here over that time. Exciting!

Categories
Dev JavaScript Optimising Process

Express snippets

Since I’m playing with Express at the moment I’ve updated my collection of snippets to include a few things I seem to be doing regularly:

Express setup

I use the shortcut “myExpressSetup” to kick off all my new Express projects. It has basically all the parts I need to get the project underway, and means I dont have to remeber each bit. This is more or less the Express equivalent of the HTML boilerplate I’ve mentioned in the past.

  'Express Setup':
    'prefix': 'myExpressSetup'
    'body': """
    "use strict"

    var express = require( "express" );
    var app = express();
    var bodyParser = require( "body-parser" );

    app.use( bodyParser.urlencoded( {
      extended: true;
    } ) );

    app.set( "view engine", "ejs" );

    app.get( "/", function( request, response ) {
      response.render( "home" );
    } )

    $1

    app.get( "*", function( request, response ) {
      response.send( "404 page not found );
    } )

    // Tells express to listen for requests (Start server)

    app.listen( 3000, function() {
      console.log( "The server started on http://localhost:3000/" );
    } );
    """

Get route

Shocking no one, if there’s one thing I seem to be doing a lot it’s displaying content on an HTML page. Using the shortcut “myGetRoute” this one basically says if the URL fits this pattern take it and display it using the “project” template.

'Express Get':
    'prefix': 'myGetRoute'
    'body': """
    app.get( "/project/:thing", function( request, response ) {
      let thing = request.params.thing
      response.render( "project", {
        thingVar: thing
      } );
    } );
    """

So, for example, I could have a URL like geekpulp.co.nz/project/banana and have it populate the project templates H1 with “banana”. If the URL was then geekpulp.co.nz/project/apple it would populate the project template H1 with Apple. Obviously later in the course, I’ll start populating things from a database and this will all make a lot more sense.

Post route

This one’s all about collecting data from a form and adding it back to the page. Again this sort of thing will make a lot more sense when I’m actually posting the data to a database. At the moment if you refresh the page everything will just return to defaut values because nothing is being saved to the backend.

'Express Push':
    'prefix': 'myPushRoute'
    'body': """
    app.post( "/addteam", function( request, response ) {
      let newTeam = request.body.newTeam;
      teams.push( newTeam );
      response.redirect( "/teams" );
    } );
    """

These new snippets are certain to change in the next week or so as I expand to doing things that are actually useful. At this stage, a lot of this stuff is just code that facilities learning. Having said that, I find making snippets for repetitive tasks a good habit to form. Ultimately the whole point is being as efficient as possible.

Categories
Dev JavaScript

NPM and a Demon

So learning node.js has been really interesting so far, I’m quite taken by it. It’s great being able to transfer my JavaScript skills from frontend to backend. One of the things I’m enjoying most about it is NPM. By their own definition:

NPM is the world’s largest software registry. Open source developers from every continent use NPM to share and borrow packages, and many organizations use NPM to manage private development as well.

Docs.npmjs.com. (2019). About npm | npm Documentation. [online] Available at: https://docs.npmjs.com/about-npm/ [Accessed 22 Mar. 2019].

So what does all this mean? As a developer, you have super easy access to a vast collection of code packages that can be used in your own projects or processes. One such package that’s saved me a repetitive task is nodemon. Nodemon does the simple job of restarting node every time I save a code change.

To install a package like nodemon you simply use the command:

npm install -g nodemon

In this command, the “-g” installs nodemon globally. This means it will work in all node projects. To run it use the command “nodemon” and your node server will fire up. Then each time you save a change to your code, bam, the server restarts to reflect the code change.

NPM has just shy of a million packages. So, if you’re in need of something to support a project, npmjs.com should be your first destination.

Categories
Dev JavaScript Projects

I made a thing: Aroha generator

So I made another thing. The only reason I’m really even talking about it is because what’s going on in Christchurch is so awful I can hardly bear it. Making new things (even simple things like this) is a good distraction.

So in an effort to cheer myself up I made a web thing that says Aroha (and basically anything else I choose) as many times as I ask it to. I did this in node.js, which I’ve never used before, so this is a good learning experience. I have no idea how to deploy anything in node yet, but once I learn I’ll put it up somewhere.

Obviously this is not something I expect to be used in anyway, but learning new things always puts my mind in a good place. It makes me think about the good things in life like change, growth and the new. Something we all need to be thinking more about, especially in dark times. I’m certainly not a perfect person, but I try hard to be a better one every day. We owe that to ourselves, we owe it to each other.

Aroha Generator in all its glory!

If you’re interested in this very random project, check it out on GitHub. If you feel like escaping for a bit then you’re welcome to add to it, or create your own, or help someone else to create one. Just remember to be kind to one another.

Aroha.

Categories
Dev JavaScript Optimising

Constantly letting down my variables

As it turns out I’ve been doing everything wrong. Well, maybe not everything, but at the very least I’ve been declaring variables incorrectly.

There are actually three different variable types in JavaScript, var, let, and const. I’ve been using var exclusively and it’s actually bad practice. So what’s the difference between each and which should I be using when?

const

Where at all possible you should use const. Unsurprisingly const is short for constant and without going into to much detail that means it’s something you know will not change. You won’t be able to use this all the time obviously because a lot of the time you need to vary the content of variables. It’s always good pratice to minimise mutability in your code and const is the ultimate example of that.

let

This is how most of your variables should be declared the majority of the time. The strength of let variables is their scope is limited to the block level. For example:

let numberOfPowers = 1;

if (numberOfPowers === 1) {
  let numberOfPowers = "1 more power than Batman"
  console.log(numberOfPowers);
}

console.log(numberOfPowers);

In this example we have two variables named the same thing, but because we are using let their scope is limited to different parts of the code so they don’t collide. So in the console, we’d see both “1” and “1 more power than Batman”.

var

This is the option you should use least often and that’s because of its scope. Unlike let, var has a very wide scope. This is either the function it’s inside of, or if it’s declared outside any function, global. Obviously, that’s not ideal because it creates a greater opportunity to have your variables collide, especially as your projects grow in size. So to revisit our example with var instead of let:

var numberOfPowers = 1;

if (numberOfPowers === 1) {
  var numberOfPowers = "1 more power than Batman"
  console.log(numberOfPowers);
}

console.log(numberOfPowers);

This time the console will only read 2x “1 more power than Batman”. This is because having a global scope means we are writing over a single global variable rather than creating two different variables with different scopes but the same name.

I can see when you’re learning why this concept might be more of an intermediate level concept. Scope can be a bit tricky to get your head around. At the early stages of learning it’s probably better to focus on core concepts rather than nuances like this, but as your skills grow I think this is an important practice to do with variable declaration.

Categories
Dev JavaScript Optimising

How to write modern JS

So you’re learning JavaScript (JS), cool. Putting all this effort in, you’ll want to be learning the modern usage of the language right? Time to get strict.

“use strict” is something I recently stumbled across, and it seems like a really important thing to be using. So much so that I’m a bit surprised it hasn’t been mentioned in the course I’m doing. As it turns out, JS is full of legacy thinking. In an effort to keep new versions of the language compatible with older versions, much of this legacy thinking was/is retained. Obviously this limits JavaScripts ability to overcome its past and improve as time goes on.

Evidently, in 2009 a decision was made to start to modernise JS with the release of ECMAScript 5 (ES5). This meant breaking compatibility with older version of JS if you decided that was what you wanted to do. This is where “use strict” comes in. To enable this “modernisation” you include “use strict” at the top of your JS files like this:

"use strict";
// code below this will be implemented the modern way
...

Since it’s been 10 years since that decision was made, all modern browsers now support ES5. So unless you need to support browsers before the dawn of IE10 then you should be turning strict mode on for all of your JS development.

This of course begs the question, why? Well, aside from staying current with the language, there are also a number of practical benefits:

  1. Modern JS throws errors on things that where previously ignored. This helps you write better, more secure code
  2. It can improve the performance of your code, sometime significantly. Sometimes the code itself is identical and you just get a free performance boost, nice!
  3. It prevents some syntax being use that future version of the language are likely to use. AKA it future proofs your code

So from here on in, I’m going to be using strict mode exclusively and only avoid it when a situation presents itself that I can’t.

As always MDN is a good source of information on both strict and sloppy mode. Now go forth and write strict code!

Categories
Dev JavaScript Projects

I made a thing: To-do list

Yep, I made another thing in JavaScript for the course I’m doing. This one’s a bit more basic, but really it’s more of cutting my teeth with jQuery sort of project rather than something anyone would actually use. It’s a very simple todo list app that lets you add and remove items from a simple list. It has no backend so you can’t save your list or anything useful like that, but the front end side of things does the job at this stage.

A simple to-do list app

If you’re interested in the code you can take a look on GitHub. Of course, you can try the app for yourself. If you find anything wrong with it you can submit an issue.

Categories
Dev JavaScript Tools

on() click()

Today I learnt the different between the on(“click”) and click() methods in jQuery.

click() only adds listeners for existing elements, so it will completely ignore any dynamically added items. So in the example below only the <li> declared in the html file will be clickable. All of the new <li> elements added to the todo list won’t be clickable:

<!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" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
    crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
</head>

<body>
  <div id="container">
    <h1>To-Do List</h1>
    <input type="text" name="" id="">
    <ul>
      <li><span>X</span> Go to potions class</li>
      <li><span>X</span> Buy a new broom</li>
      <li><span>X</span> Visit Hagrid</li>
    </ul>
  </div>
  <script type="text/javascript" src="assets/js/script.js" charset="utf-8"></script>
</body>

</html>
// check off specific todos by clicking
$( "li" ).click( function () {
  $( this ).toggleClass( "completed" );
} );

// click on x to delete todo item
$( "span" ).click( function ( event ) {
  $( this ).parent().fadeOut( 300, function () {
    $( this ).remove();
  } );
  event.stopPropagation();
} );

// add new item to todo list on keypress
$( "input[type='text']" ).keypress( function ( event ) {
  if ( event.which === 13 ) {
    var todoItem = $( this ).val();
    $( this ).val( "" );
    $( "ul" ).append( "<li><span>X</span> " + todoItem + "</li>" );
  }
} );

To get around this, instead of using click() we use on(“click”). Unlike click() on(“click”) will add listeners for all potential future elements on the page. This makes all the dynamic content, like the new items in our todo list app, work flawlessly. So the updated code would look like this:

// check off specific todos by clicking
$( "ul" ).on( "click", "li", function () {
  $( this ).toggleClass( "completed" );
} );

// click on x to delete todo item
$( "ul" ).on( "click", "span", function ( event ) {
  $( this ).parent().fadeOut( 300, function () {
    $( this ).remove();
  } );
  event.stopPropagation();
} );

// add new item to todo list on keypress
$( "input[type='text']" ).keypress( function ( event ) {
  if ( event.which === 13 ) {
    var todoItem = $( this ).val();
    $( this ).val( "" );
    $( "ul" ).append( "<li><span>X</span> " + todoItem + "</li>" );
  }
} );

jQuery has some excellent documentation. So if you need to drill into the specifics of any particular method (like on() or click()) be sure to RTFM.

Categories
Dev Geekpulp JavaScript Tools

What is the state of JavaScript?

This JavaScript thing is really catching on eh? As the name suggests, “the state of JavaScript” survey gives a snapshot view of JavaScript development. What everyone (over 20,000 developers anyway) is using and enjoying or otherwise. It also gives a general sense of the direction things are going in. As with the StackOverflow survey, I found it well worth a read. It’s also beautifully presented.

Some of my main takeaways:

  • React is where it’s at from a front-end framework perspective
  • Express seems to be the stable go to back-end framework for Node.js
  • GraphQL appears to be the rising star of the data layer, but Redux is the player to beat
  • There seems to be a range of good options with testing, but the community seemed to enjoy Jest the most
  • Building desktop and mobile apps using JavaScript seem to be a two player game at present. Electron for desktop and React Native for mobile. This space does have some competition on the rise though. Flutter looks particularly interesting
  • VS Code dominates text editors by such a large margin, I really need to give it a second look. I haven’t seen anything that makes me think I’ll move from Atom but I’m open to the possibility

Have you read the survey? Did I miss anything you found particularly interesting?

Categories
Dev JavaScript

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.