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.