Section 3: Functions, Objects, Shorthard Shortcuts and Async-ing Better

Overview: Today we are going to go over a variety of things, much of it deals with the inner workings of Javascript itself. We will take a look at functions, objects and inheritance, some shorthand shortcuts we can use, as well as how to use jQuery AJAX better.

Functions as first class citizens!

Maybe you have head this before about Javascript, or maybe not. Either way, this is a phrase people use to describe functions in Javascript. Why? And what does it mean?

The term "first class citizen" means an entity which supports all the operations generally available to other entities. How this can apply to Javascript is comparing the operations and things you can do with a function, versus with other entities such as integers, strings, booleans, etc? So if this rule is right, we can treat functions as if they were a data type's. This means we should be able to pass them as arguements, return them from functions, assign them to variables, etc. Let's try some of these out then.

We can assign them:

See the Pen functions as first class - assignable by Mike P (@mikedemo) on CodePen.

We can return them:

See the Pen functions as fist class - returnable by Mike P (@mikedemo) on CodePen.

We can pass them:

See the Pen functions as first class - passable by Mike P (@mikedemo) on CodePen.

They can be assigned as properties:

See the Pen functions as first class - as properties of objects by Mike P (@mikedemo) on CodePen.

So now we can see why functions as 'first class citizens' in the world of Javascript. We are almost able to treat them as a data type, which comes in handy all the time when passing callback functions... speaking of callback functions:

Callback Functions

The fact that Javascript basically treats functions as data types, allows Javascript to use callbacks. This pattern is extremely popular due to the asynchronous nature of Javascript (which we will go over shortly), and is something to utilize if you are not already. The basic idea is that you will pass a function to another function, but the function that was passed in will not execute until the original function finishes. Here is an example:

See the Pen using callbacks by Mike P (@mikedemo) on CodePen.

This is a classic example of doing something with a callback. We start execution by calling
longRunningFn
and passing it the
notify
function and the string
<br>Process is done!<br>
, these are the callback function and its parameters that we are going to execute in the
longRunningFn
function when it completes (in this case instead of an HTTP call we will do a 3 second timer). In the mean time, we see our Javascript does not wait for the timer to complete before executing the next line of code, the
doOtherStuff
function. So how will we ever know when the original
longRunningFn
function completes? Thats where callback functions come in to save the day, if it wasn't for the callback function in
longRunningFn
, we would never know if that function completed or not.

jQuery AJAX

Javascript's ability to make HTTP calls via AJAX is extremely useful and is probably the primary reason it has become so popular. But, because they are HTTP requests going to a server, we run into the problem of AJAX calls taking a few milliseconds, maybe even a few seconds. Here is a live example:

Bad Async

See the Pen bad jquery async example by Mike P (@mikedemo) on CodePen.

This example has a button that when clicked, will check to see if we have access or not, and enable or disable the button based on the response. We set the
hasAccess
variable to false, then check if we have access. We are going to a random API that returns some data, and we are saying that as long as some data is returned, access is allowed. This API will 100% of the time return data, so in theory my
hasAccess
variable will become true, and the button will never be disabled.

As you can see, that did not happen. If we open the console and take a look, you can see the
checkAccess
function fires right away, however the conditional
if (hasAccess)
will execute before our
checkAccess
function has a chance to complete. jQuery's
ajax
function has you covered here, but there is a few ways to do handle this.

Good Async

See the Pen better jquery async by Mike P (@mikedemo) on CodePen.

Here we are utilizing the jQuery
ajax
function to help us with our asynch problems. The property
success
will execute (if it has been assigned a function) upon a successful response from the server. So, we caa just do our disabling logic in there right? Yes and no. It solves the problem, but not in a very maintainable way as far as the code is concerned. What if the logic that needs to be done to enable/disable the button becomes much more complex? What if that
success
function itself needs to execute an AJAA call? Our code is going to look really bad, and our function that makes the AJAX call will not be reusable since its result has specific logic coded into it.

We need to take the logic out of the AJAX call
success
function, but where can it go? And how can we make this AJAX call more re-usable?

Best Async

See the Pen promise async example by Mike P (@mikedemo) on CodePen.

jQuery
ajax
will return a Promise interface, referred to sometimes as a deferred object. We will talk more about deferred objects and Promise's in a more advanced tutorial, just know these are special types of objects. Because jQuery
ajax
returns an object, we can assign it to a variable. The jQuery
ajax
deferred object has a method called
.then
that will not execute until the deferred object has completed its task. We can utilize
.then
as well as the fact that we can assign our
ajax
function to a variable to make our code simple and clean. The function that makes the AJAX call is re-usable now, since it simply returns as a deferred object with the HTTP response in it, and we have kept the logic we need to run on the request data seperate.

Object Inheritance

Javascript uses objects for everything, there is no question. And normal, plain Javascript objects are extremely simple, there is really nothing to them. Javascript however does have a bit of an unorthodox way of doing object inheritance, let's take a quick look:

Person > Developer > DevManager

See the Pen inheritance by Mike P (@mikedemo) on CodePen.

This is a simple example of object inheritance in Javascript. Javascript objects can inherit from one another, and can almost be treated as classes. Javascript refers to this as the
prototype chain
or
prototypical inheritance
. As objects inherit each other, each of their new functionlties is added to the
prototype chain
.

Our example shows the objects being defined using a constructor
function Person (name, gender, age) {
and then assigning all of the passed in values to properties I am declaring of the object. Using this constructor is part of what makes this object a 'prototype' and not just any other object or function.

If I want to later assign properties to the object prototype, I can simply add them but doing
Object.prototype.property = value;
such as in
Developer.prototype.typeCode = function () { }


The
call
function that is run on the parent object in the child object's constructor is essentially like calling the superclass/parentclass's constructor in normal class based languages.

With so many Javascript frameworks coming out now, there is not a high probability that you will be doing a lot of object/prototype based inheritance yourself, most Javascript frameworks handle all of this for you and just allow you to declare classes, but this is what is going on under the hood.

Random Object Pitfall

Objects do not have an order, they are not indexed in any particular manner, and there is no gaurentee that they will stay in order. Objects are more like collections since they have no real order, and you should never count on the order of and object, use an array or an array of objects instead.

Out of Order

See the Pen order not gaurenteed by Mike P (@mikedemo) on CodePen.

In Order

Using an array of objects, we can keep our collection in order.

See the Pen use array of objects instead for order by Mike P (@mikedemo) on CodePen.


Shorthand

Before we go let's take a quick look at some cool shorthand tricks, as well as the loosness of Javascript types so we can see how these might help us write less code. Remember, in Javascript, you are on the clients machine so you are limited by their capabilities. Less code is generally better, and can make a difference over hundreds of thousands of lines. Let's take a look at the double not !!.

!! Not Not

Using 2 'not' operators in a row is a good way to convert things that should be objects into boolean values. In the example below, we are checking to see if the browser is IE, and if it supports geolocation. If one of these is true, it will return an object, otherwise it will return null. Rather than add in logic to check if the variables are objects or null, we can apply the double not to get the boolean equivalent; if the variable is an object, it will be true, if it is null, it will be false,

See the Pen using not not by Mike P (@mikedemo) on CodePen.

Ternary

Because of the way we assign properties to Javascript objects, often times we can use ternary conditionals to change properties. Take a look at the code below:
Too much code

See the Pen ternary and shorthand bad example by Mike P (@mikedemo) on CodePen.

A lot less code for the same result

See the Pen ternary and shorthand good by Mike P (@mikedemo) on CodePen.

Truthy and Falsy

I will leave you with the code below to look at. This is showing what evaluates to what in Javascript, is the point I am trying to convey is how loose the types are. What you should take away from this is not that Javascript types are weird because they are very lose when using the '==' but rather think about how this can apply to cuttind down on logic and conditionals.

See the Pen truthy and falsy by Mike P (@mikedemo) on CodePen.