Labels

javascript (9) css (3) babel (1) nodejs (1) webpack (1)

Friday, August 4, 2017

Primitive Data Types (JavaScript)

Each language has basic data types known as primitive types. You will be using these types extensively as you program in Javascript.

I won't go into too much detail on each one but will just give some basic information.

The first type is boolean. This only has two values: true or false.

Next is null. This means it is nothing and will evaluate as false.

There is also a number type. This includes integers (1, 2, 3...), floating-point numbers (1.2, 2.3, 5.3), and doubles (same as floating-point in JavaScript). JavaScript doesn't have the concept of doubles and floats like other languages have.

Another type is the string type. This is any text you display or receive from HTML input like ("Hello World!");

Finally, there is the undefined type. If something isn't defined it is undefined. You can even do something like var x = undefined;, though you could argue that it is not longer undefined because you just defined it. This will also evaluate as false.

Hopefully you have a better understanding of the basic data types of JavaScript.

Variable Basics (JS)

In this first part of the Basics Series, we are going to look at variables in JavaScript. First we will look at declaring and using variables and then discuss some of the gotchas. I will leave ES2015 variable declaration until after we discuss some other fundamentals.

First things first, head on over to https://plnkr.co and start a new project. From there go to script.js in order to edit it.

For the first exercise, let's declare a variable using the var keyword.

var x = "x";

What we did was declare x to be variable and assigned it the string "x".

If you now type in: document.writeln(x); you will see that "x" is printed to the Live Preview.

Please note that document.writeln() is not really recommended and Plunker will let you know that. We are doing it this way for now to simply display some text to the browser.

One of the things you can do with strings is use the + operator to concatenate them. Concatenate is a fancy term for join.

So if you type document.writeln(x + "y"); you will see "xy". Easy right? You also could have easily assigned "y" to a variable and added the variables together to produce the same effect.

Strings will be very useful in your journey since HTML is basically one large string.

Moving on, let's look at numbers.

Go back to where you declared "x", declare a variable called one and assign it a value of 1.

It should look something like this:

var x = "x";
var one = 1;

Doing a document.writeln(one); you will get 1;

Now here is where some trickiness occurs and I want you to see it first hand.

What do you see when you type document.writeln(one + "1");? What did you expect to see? JavaScript automatically converted the type of the variable one to a string which is why you got 11 instead of 2.

Now try document.writeln(one + 1); Is that more of what you expected? Keep this automatic type conversion in mind.

Speaking of type conversion, sometimes we wanted to check if a variable is the same as another value. In most languages you would use the == operator. Let's try that.

What is the output of document.writeln(one == 1);? That's exactly what we expect right? We get a true value.

What about if we did document.writeln(one == "1");? Still true right? JavaScript did an automatic type conversion for you.

Most of the time that is not the desired result. We want to know if they are exactly equal.

Try this: document.writeln(one === "1"); What did you get this time? It is false because the automatic conversion does not take place and the integer 1 does not equal the string "1".

This, however, will give you true: document.writeln(one === 1);

One thing you could do is use parseInt(). This will take your string "1" and make it the integer 1.

For the last exercise, try document.writeln(one === parseInt("1"));

You should get true now.

Just for a quick reference, you should have something like below for your code. Please don't just copy and paste this. Actually try to type it and work through it.

var x = "x";
var one = 1;

document.writeln(x);
document.writeln(x + "y");
document.writeln(one);
document.writeln(one + 1);
document.writeln(one + "1");
document.writeln(one == 1);
document.writeln(one == "1");
document.writeln(one === "1");
document.writeln(one === 1);
document.writeln(one === parseInt("1"));

Friday, April 7, 2017

Automatic Semicolon Insertion (ASI)

I just ​watched a video on best practices for JavaScript. Now I have always been in the camp of "Use semicolons!" and this video didn't change it. There are so many errors that can creep in if you don't know the rules of how ASI works. For instance:

console.log("Log")
[1,2,3].forEach(function(value) {
   // stuff
})

This previous line of code will cause an error because brackets are perfectly acceptable after an object as far as JavaScript is concerned.

Another thing brought up was using curly braces on the same line of the function or anything else that is using them because if you try to do something like this:

function() {
   return
   {
       x: x
   }
}

You will get an error because ASI will put a semicolon right after return. The way to fix this would be to put the curly brace on the same line as return. As an aside, this means to put curly braces on the same line for everything to keep things consistent.

Another reason the author suggested for using semicolons was to stay consistent with other C-like languages because JavaScript itself is a C-like language.

I don't want to tell you how to live your life but I would sure like to make things easier on you so USE SEMICOLONS!...Please.

Update:

In case you needed more convincing, this is from the Google JavaScript style guide: Every statement must be terminated with a semicolon. Relying on automatic semicolon insertion is forbidden. Semicolons are required

Node Web API

Recently I have been working with some Web API and I am forced down the path of Java. So far, I must say that I am confident in this assertion: creating a Web API is much simpler in Node.

It's not that I don't like Java but I am more familiar with Javascript and Node seems to be more suited to the task of Web APIs. This isn't to say it is the best and Java certainly has its own advantages. For instance, Java is more powerful. As a side note, I have made Web APIs in C#.NET and I am pretty impressed with their implementation.

All that aside, I wanted to show a quick how to on making a Web API in Node.

let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let cors = require('cors');

app.use(bodyParser.json());
app.use(cors());

app.post('/api/v1/:resource', function(req, res) {
   let resource = req.params.resource,
       body = req.body;
       
   // do something with the JSON in the body
   
   res.sendStatus(200);
});

app.get('/api/v1/:resource', function(req, res) {
   let resource = req.params.resource,
       body = getData(); //ficticious method for getting the resource
   
   res.send(JSON.stringify(body));
});

app.listen(8888);

So there is a very simple REST interface using Node+Express. You need to install Express, bodyParser, and cors for this to work but that isn't too difficult.

npm install --save express cors bodyParser

bodyParser allows for receiving JSON from the POST body and cors is used to allow cross origin requests. These are not necessary for a simple Web API but you may find yourself needing them.

app.post tells express to run the provided function whenever the url is POSTed to. In this instance, :resource will be whatever is put in that location of the URL.

http://domain/api/v1/users maps :resource to users

app.get works similarly but instead of changing the data, it returns it in the body of the response.

Finally, app.listen tells the server to listen for requests on the specified port.

Start it up using npm start and you are ready to go!

Friday, March 24, 2017

Webpack + Babel

The purpose of this post is not to make anyone an expert with Webpack or Babel but to simply demonstrate a very basic setup that uses Webpack for bundling your ES6, or ES2015, code using Babel. There is an associated Git repo you are free to clone and change however you like.

The first thing you want to do, as with most projects, is set up your environment:

npm init

This will ask you for some information so just fill it all out to get setup.

Then next thing you will want to do is install the required dependencies:

npm install --save-dev babel-loader babel-core babel-preset-env webpack

As you can see, this will install Webpack and the required Babel plugins and set them up as a dependency for your project in your package.json file.

From there, all we need to do is write some code!

Here is a very simple webpage that will display the name you set in JavaScript. Here is the complete source:

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Webpack + Babel example</title>
    </head>
    <body>
        <h1 id="example"></h1>

        <script src="dist/bundle.js"></script>
    </body>
</html>
src/example.js
/**
 * This uses ES6 modules to export the Example class
 * which takes a value for name as a constructor argument.
 * It returns that name with the getName function.
 */
export default class Example {
    constructor(name = "Webpack") {
        this.name = name;
    }

    getName() {
        return this.name;
    }
}
index.js
// This imports the class Example from example.js
import Example from './src/example';

// Now using it is as simple as...
let example = new Example("Webpack + Babel"),
    h1Example = document.getElementById("example");

h1Example.innerText = example.getName();
webpack.config.js
let path = require('path');

// You can view the docs for Webpack but basically, entry is 
// the file to start with and output is where you want it to go.
// There is a lot more you can do with this.
module.exports = {
    entry: './index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

Once that is all done, you can simply type webpack at the command line and Webpack will find the webpack.config.js file at the current working location and then bundle your JavaScript. We have it set to go to the dist folder as bundle.js which will automatically be created (directory also) if it is not already there.

One thing you can also do is type:

webpack --watch --colors --progress

This will automatically run webpack any time there is a change to the code.

Now that you have a basic understanding on this Webpack + Babel thing, check out Webpack's guides to learn more. I hope this helps you in your future projects.

You can view the repository here in case you wanted to use it as a starting point.

Saturday, November 26, 2016

How to Make a Web App Part 2 - User Stories

When I first started coding I liked just diving in and programming. There is still that urge to just jump in and start slapping functions together to make something that works but I want you to imagine for a moment if other professions worked that way. Let’s say a construction company was creating a high rise without any sort of blueprint. They have some sort of vision of how they want it to look and work but they never sat down to create a way forward. They just started slapping beams together as they went and then built walls, added doors and windows, electrical outlets, elevators, and whatever else goes into a skyscraper as they went. Would you want to work in that building?

There is a reason architects design the buildings beforehand and a lot of work goes into making the blueprints. They know everything will work as intended. If you have no intentions going in then nothing will really work as intended.

There are many different ways this can be done. We won’t really get too deep into the different software methodologies so I encourage you to look these up and learn more about them for yourself. The main software methodologies are Waterfall, Spiral, and Agile. Waterfall is a lot of documentation up front. You have your requirements documents, use cases, class diagrams, and a whole lot of other things planned up front. As you can imagine this process can take a long time before working software is delivered. Typically between 6 and 18 months. This would be like the architect who has everything planned up front before any construction takes place. A drawback of this approach is changes are usually quite expensive because now everything needs to be planned again.

Spiral is like waterfall where you still have a lot of documentation and planning but releases occur much more frequently. We are talking several months to a couple years. Changes are not as expensive because the system is not being completed in one big chunk but several smaller ones.

Agile prefers working code over documentation so there is little documentation. It wants more interaction with customers. It says to deliver working code early and often. This is what we are going to use while building our app. There are many different flavors of Agile I encourage you to study on your own and many of them work concurrently. A lot of times you’ll hear about Scrum and Kanban or XP. They all have different methodologies that work well together. Again I will not focus on any specific discipline but leave that up to you to discover. You should also choose which methodology, Waterfall, Spiral, or Agile, to use based on which is the best tool for the job.

So rather than write a lengthy requirements document we are going to start our first Sprint with some user stories. A Sprint comes from Scrum and it is just a period time to get some amount of work done. A sprint can be one week to a couple months so you would work on user stories for the entire sprint and nothing more. If you don’t finish you hand over what you have anyway and save it for the next sprint. Your team’s speed, or velocity, is measured in how many story points you complete per sprint. You really can’t compare your velocity with another teams’ because it is completely dependent on how many story points your team attributes to stories and should only be used as estimates for how many user stories can be completed per sprint. We are not going to worry about this with our app and our first and only sprint will be however long it takes us to finish.

After that long explanation of what we are doing, let’s get started! Whether you are working for yourself or a customer, you have some form of stakeholder. If you are working with the customer, you want to build what they want. If for yourself, you build what you want. Simple as that.

Since we are working for ourselves, let’s start coming up with some user stories for a web app idea. For our idea (well really my idea), we want to build a grocery list web app that we can add, remove, and modify grocery items and put a check mark next to them to show completion. We will obviously need to have some form of login and a way for users to save their grocery lists. It would also be nice if you could share lists with friends or allow spouses to use the same list. For this sprint, we really don’t care if the list is archived or not once it is completed but this is something you could easily do on your own for practice. You could create a list of lists, if you will, or just have them automatically deleted to let the user make a new list. For now we will just allow the user to remove checked items and be able to add new items all using the same list.

Now that we have what we are trying to do, let’s make the user stories we are going to work on for this sprint. The format of a user story is very simple as it is designed to be created by any stakeholder but it captures what is wanted without going into a lot of detail. The format I like best goes like this:

As a shopper
I want to add a grocery item to a list
So that I can remember it while I’m shopping
The first line shows who is taking the action. The second line shows what task needs to be done and the third line shows what will be achieved by the user completing the task. For this sprint we will work on these user stories:
As a shopper
I want to add a grocery item to a list
So that I can remember it while I’m shopping
As a shopper
I want to remove a grocery item from a list
So that I can get rid of an item I no longer need
As a shopper
I want to be able to place a check mark next to an item
So that I can see progress of what I’ve already got
As as shopper
I want to be able to login to the application
So that my list will be remembered

Even though we discussed a few more ideas, these should be a perfect starting point for our first release. Remember we release working code early and often so this will get our app functional and then in our next sprint, we will add some of the other features to make it better.

Previous: Introduction
Up next: UI/UX Design (coming soon)

Friday, November 25, 2016

How to Make a Web App Part 1 - Introduction

My goal with this series is to walk a beginner or novice through the process of creating a web application. This isn’t meant to increase your proficiency beyond that of a beginner with any language but to give a starting point that can be built upon. I will delve into HTML, CSS, and JavaScript to teach the basics but there are plenty of books written on these that will explain the concepts in much more detail than I will so I am relying on the reader to use other resources to increase their skills.

What I will do, however, is teach the necessary parts of the languages and in a different way than I learned. I learned HTML way back in the early 2000s and picked up CSS and JavaScript at a much more involved level much later when I got into Web apps. In each of the books I read, I learned how the language worked and what you could do with it. I then relied on years of practice, research, and college to learn best practices and processes. For example, when I learned JavaScript I did not learn how to write it to be testable. This was something I picked up later. I also didn’t have a process in place to go from nothing to a web app.

All that being said, I want to bring the reader through the process of building a web app with these things in mind. If you are new to JavaScript, I will teach the basics alongside testing. I will bring in user stories and sprints to help the reader not just learn JavaScript, but how to use it effectively to create an application. Again, this is something I scoured the internet and attended college classes to try and bring together. I want to teach everything I learned from the very beginning. I will not go very deep with any of these concepts but my hope is the reader will get a general idea of what it takes to make an app and then expand their knowledge using other resources to build anything they wish.

With that in mind, we will get started with the basics of building a web page and then expand upon it from there as we build a simple web app. Enjoy!

Up next: User Stories