TagFunctions

Building an Analog Clock in JavaScript

In our final JavaScript example, we are going to be building an analog clock using JavaScript and the HTML canvas element. The HTML canvas element allows us to create graphics inside of a web page and it comes with several methods of its own as we will see. This example will make use of all of the different JavaScript concepts that we have learned. 

Getting Started

To get started we first need to create our canvas element. To do this, we need to define the width and height of the element that will render our clock face and hands. Basically, we are making a box and then mounting a circle inside of this box.

We’ve defined our canvas and if we were to open this piece of HTML in our browser we would have a solid gray box. We need to add our clock face and then add the logic that runs the clock using JavaScript.

JavaScript Clock FaceWe bound our canvas to the element variable then created a 2d object with our graphic variable. We then used the height of our box to calculate the radius of the circle. We used the radius to map the graphic variable to the middle of the canvas box. We then decreased the size of the radius variable by 90% so that we could draw the circle correctly with the arc method. Finally, we defined a fillStyle for the circle element and filled it with white. We created a startClock function and ran it because without it, we would not actually draw the circle.

We will now refactor our startClock function so that the code will be more efficient and so that we will have all of the similar functions in one place. We will do this by creating three separate functions that will be inside of this startClock function. One function will draw the entire face, one will draw the numbers on the clock and the other one will give the clock the logic it needs to work.

Refactoring for Effect 

In our dFace function, we create two separate elements; a white circle that will contain our clock and a small black circle in the middle that will act as our clock center. As you can see by the two separate blocks of code, the only difference is that in the 2nd arc function we decrease the radius to 10% of it’s size. If we were to run this code without the other two functions, we would see a white circle with a small black circle inside of it. Now let’s place the numbers into the clock.

In this function, we use a for loop to loop through the numbers one to twelve. As we loop through each number we place that number 85% of the original radius away from the center of the circle and draw it as ~60px size text. We then make sure that each number is six degrees away from the last number because 360 degrees /12 is six. Let’s look at the startTime function and the logic that will make the hands move.

We have most of what we need now, however, our drawHand function is not a method for the canvas and we need to define it to render the hands to the canvas. As you can see, this is a case of using a function to create reusable code as we use drawHand three times in the startTime function.

Bringing Our Code to Life

JavaScript ClockThis is our mostly finished code. We have our functions which render everything and if we reload the browser screen it will change the time but we want to automate the clock itself and not have to reload the screen every second. To do this, all we need to do is call the setInterval function in our code and pass the startClock function into it. We then pass as a second argument, the amount of time we want to wait before the function gets called again which in this case is 1000 milliseconds. The setInterval function allows us to get away with a bit of trickery. As with most graphics, we are just re-rendering the entire clock every 1000 milliseconds. Our completed code base will look something like this (you may also visit our github for the source code).

What Now?

In this post, we took a look at an HTML canvas example and created an analog clock using HTML and JavaScript. We broke down all of the steps and functions used inside of the code. This example and post will be our final code example for the JavaScript tutorial (at least for now). It is very likely that we will revisit some of the node.js libraries like react.js and angular.js. We will also probably go over TypeScript at some point which is a superset language of JavaScript. We will also cover some live coding tutorials on our Youtube channel so keep your eyes peeled. 

This tutorial is just designed to get you started. To become a JavaScript god you need to practice and start making code on your own. You can do this at Codewars and by running other code Katas. The best way by far for you to become a JavaScript master is to just sit down and code. 

Our next tutorial will cover Golang, a low-level imperative language that was built by google. 

Object Constructors in JavaScript

Today, we are going to take a more direct look at objects. Our first encounter with objects introduced us to their properties and methods. We looked at two specific ways of creating objects, the use of object literal notation and the new Object() function. In this post, we are going to look at object constructors.

Factories for Objects

Object ConstructorsWhen you define an object using the object literal notation you are defining a specific object instance. To leverage the power of objects as a data type, we need a way to streamline the creation of specific types of objects. Our original object example was that of a Person object. This was a good example for that lesson, however, it only works well for describing one specific person. What if we want to create a data type that can be applied to many different people? This is where object constructors become relevant.

Object constructors work like factories. They allow the programmer to create a function which will output multiple objects with the same general data shape.

In this example, we created a Person object constructor which takes three parameters. We assign these parameters to variables inside of the function which then allows us to create multiple instances of this object with different arguments being passed. If you call one of the three instance variables, you see a return of a Person object with the specified values. But then, what is that weird this keyword?

What The Hell Is this?!?

this keywordBefore we go any further, we need to talk about the this keyword. As you can see in the constructor above, we are using the this keyword three times in the variable assignments. What the this keyword allows us to do is to refer to the Person object directly even though it hasn’t been created. We are essentially saying that the Person function and object owns the firstName variable, the lastName variable, and the age variable. It allows us to differentiate the variables owned by the object from the parameters being passed into the function. this is basically a reference to the object itself. Here is a more general object constructor function.

The Car object constructor in this example uses different variable names for the parameters and the function attributes. Also, when you make a new instance of the Car object, you automatically get the object returned to the console. The this keyword might seem a little abstract at first but as you use it more you will get used to it.

Naturally, we can also create constructors that have methods inside of them. Look at this augmented Person object constructor.

In this example, we can call the greeting() function on any of the instance objects that we create with the new Person constructor using dot syntax. Calling the greeting() function will fire the anonymous function which was declared in the constructor.

Natural Constructor Functions in JavaScript

JavaScript also has it’s own native object constructors. Below is a chart with some of the different built-in JavaScript object constructors. Some are very straightforward and others we have already talked about. There are also a few that we have yet to talk about.

Object Constructors - Mind FuckWe’ve alluded to this many times before but most items inside of JavaScript are Objects and almost everything inside of JavaScript is treated as an Object in some way. The larger exceptions to this rule are the primitive types like numbers and strings. As a result, JavaScript still treats primitive types in a similar fashion to objects even if they aren’t objects themselves.

new Array();Creates an Array Object
new String();Creates a String Object
new Number();Creates a Number Object
new Boolean();Creates a Boolean Object
new Object();Creates an Object Object
new Date();Creates a Date Object
new Function();Creates a Function Object
new RegExp();Creates a new Regular expression Object

Closing

In this post, we introduced the concept of Object constructors in JavaScript. We showed a few examples of Object constructor functions and talked about the this keyword. Our next post will delve deeper into the world of objects as we look at prototypes and getter and setter functions.

Objects in JavaScript

We’ve mentioned objects a few times in past posts though we really haven’t explained what they are. We know that functions are related to objects and that arrays are also related to objects.  We also know that objects are one of the core data types in JavaScript. So what exactly are objects in JavaScript? An object in JavaScript is a complex data type, similar to an array, wherein values are paired with names. Each of the items in this list of values is called a property. Like an object in real life, objects in JavaScript have properties and can have behavior.

One of the most common examples of an object in JavaScript is that of a person object as seen below.

This object has three properties, a first name, a last name, and an age. Each of these properties can be called in a similar fashion to that of a piece of data in an array, except instead of using an index, we can call them through the key names, firstName, lastName, and age. Another difference from calling arrays is that we must use quotes around our key names to call them in this fashion.  Notice that instead of using square brackets like with arrays, we use curly brackets for defining objects in JavaScript like we did with functions.

When you define the person object in the JavaScript console, you can access the data inside using the “dot” syntax or the “square brackets” syntax (the “dot” syntax is more heavily used and idiomatic in JavaScript).  You can also change the values inside of an object though it is through a different syntax than with arrays or variables. Also, unlike the primitive data types in JavaScript, we can not copy an object like we can with a variable, instead we can only refer to the object.

In the example above, when we create a reference to person with the variable anotherPerson. We are not copying the person object to another container. This is why when we change the age property in the person object it also changes in the anotherPerson object.

The Attributes of Object Properties

kettle-objectThe object properties each have three specific built-in attributes that are not really demonstrated in these examples.  All object properties have a configuration attribute which specifies whether or not the property can be deleted or destroyed. Object properties also have a writable attribute which specifies if they are changeable or mutable.  Finally, all object properties have an enumerable attribute which specifies if they can be returned in a for-in or (for/in) loop structure. We will discuss these attributes further when we start to talk about getter and setter functions but for now, let us look at some of the ways that we can create objects in JavaScript.

The object we created above was created using object literal notation.  Another way to create objects is through a constructor, in a similar way that we can create arrays. Object constructors use the new keyword, like arrays, and they use the object keyword.  Below is a new person object that also has a function embedded in it. Properties that contain functions are also called methods (more on this later).

The two objects above are exactly the same but were created through different means.  As we will see when we talk about more complex objects, these two different ways of creating objects both have their advantages and disadvantages.

Note that if you wish to call the function or method built into the object you must use parenthesis. If you type out person.hello, the console will return the function format and not actually run the function, which is the case for all functions.  This function is what’s called an anonymous function. The function itself does not have a name and it is just referenced by the person.hello property. We will talk about these types of functions later.

Conclusion

In this post, we introduced the concept of objects in JavaScript. We talked about the basic attributes of objects and some of the basic methods which are used to create them. In our next post, we will start to discuss “scope” and continue our discussion of both Objects and Functions.

Fun with Functions in JavaScript

Today is the day that we finally start to put together all the pieces we have been learning in all of our past posts.  Today, we talk about functions in JavaScript. Functions are a very powerful feature that exists in almost every modern programming language.  In fact, an entire subset of languages, functional programming languages, use functions as their main way of reasoning about data. Technically, JavaScript falls under this category as well, though it is an impure functional programming language because it uses mutable data.

Functional Functions

So what exactly is a function? Put simply, a function is a piece of code that allows you to do “something” with your data. You may use a function an infinite number of times just by invoking its name in a similar way to variables. Unlike variables, functions have behavior and are complex data structures that perform tasks.

In JavaScript, we can define and invoke a function like so:

function-diagramIn this template example, notice that very general terms were used to describe what we are looking at.  This is because functions can take on many different formats, they can have many parameters (some of which can be functions themselves) and they don’t necessarily need to have a return statement. Though, you’ve probably noticed while working with your JavaScript console that any statement you input returns something even if it’s just undefined.

Functions as Arguments

We’ve discussed a few different functions prior to this and one of the best examples is our console.log() function. The console.log function prints whatever it’s arguments are to the console itself and returns undefined. Believe it or not, you may actually pass console.log() to itself like so.

This will print out "hello \n there" undefined "how are you doing?" undefined and then return undefined.  Note, \n is a way of splitting a string into two lines, it’s called the newline character with the backslash being an escape character (it “escapes” the string with whatever directly follows it). Let’s look at an example of a function to better understand how they are useful.

Abstraction Using Functions

Say we want to write a program that changes Fahrenheit to Celsius (this is a very classic programming example). We could write it using variables and basic math easily with what we’ve learned thus far.

functionsThis will do what we want and it will convert our 90 F to 32.22222222222222 C and print out a string that says, "The temperature is 32.22222222222222C". However, this type of coding becomes clunky when we want to convert multiple different temperatures to Celsius, especially if we are dealing with user input. Wrapping the equation in a function will allow us to “freeze” the code for multiple uses; this is a form of code abstraction.

Notice that you can pass variables as well as numbers directly to the function as arguments and that you can also embed the function in a string statement through the use of concatenation.  Open your console and try throwing as many numbers as you want into this function.  If we want to keep our code even more compact, we can also put the console.log part inside of the function itself as well and drop the return statement.  Now, calling the function will return undefined instead of a number.

Functions are considered “instance objects” in JavaScript though if we call the typeofoperatoron our c_to_f function it will return the type "function". Calling typeof on c_to_f() will return undefined because we are invoking or calling the c_to_f function with the parenthesis even if there are no arguments being passed into it. Running the typeof operator on function with arguments being passed will return the return value type because it runs the function before typeof runs.

One more thing that we need to discuss before closing out today is the difference between a parameter and an argument. While you might find that many people use these words interchangeably (It may have been done in this post), they are not technically the same thing. A function parameter is the name of the variable when you are creating the function; the variable names inside the parenthesis.  These are the variables that are listed in the function definition. An argument is an actual value that is being put into the function when it is being called. Basically, anything inside the function definition parathesis is a parameter and anything inside the function parathesis when it is being called is an argument.

Conclusion

Today’s post covered very basic functions. We talked about how to build a function, what purpose a function serves, and we touched on how JavaScript views functions. We also talked about arguments and parameters, and we looked at a fun example of passing a function into another function. Our next post will start to talk about objects and will expand upon functions further.

As always, feel free to comment with feedback and constructive criticism if you feel that we forgot something.