TagJavaScript

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. 

How to Write Idiomatic JavaScript

JavaScript is a language that has very few constraints on how you can write it. As a result of this, programmers can have a tough time writing idiomatic JavaScript. If you follow the proper guidelines, then you will not have this problem. In this post, we will talk about these various guidelines and how you should follow them when writing your JavaScript.

Writing Variables Idiomatically

varUsing a lot of global variables can be one of the largest mistakes that a JavaScript programmer can make.  Because of the lack of scope in JavaScript, global variables are extremely susceptible to unwarranted modifications. This is why ES6 introduced the block binding keyword let and the reason why programmers use closures. When writing a program in JavaScript, it is always better to try to find a way to make your variables local.

Generally, you want to declare and initialize your variables at the beginning of a block of code. Doing this is more idiomatic JavaScript and it creates cleaner code. Doing this will also help reduce the number of global variables in your code and reduce the possibility of re-declaring variables redundantly.

JavaScript naturally hoists variable declarations towards the top of a block. If you already have your variable declared and initiated you will not have to deal with the side effects that can occur from this hoisting. Remember, the initialization of a variable is not hoisted; only the declarations are.

Working with Types Idiomatically

When working with primitive types, it is best to not define them as objects. Declaring a primitive type as an object using the new keyword can slow down your code significantly. It is more idiomatic JavaScript to avoid using the new keyword even for objects themselves. Instead, use the literal syntax rather than the constructor syntax when defining a new variable.

ObjectsIn the examples above, you can see that each type has its own literal notation, this includes functions.

When dealing specifically with numbers and strings, try to avoid type conversions. When writing idiomatic JavaScript, it is best to avoid using variables and functions that can accidently lead to producing NaN. As we’ve already seen, NaN can be extremely detrimental to a code base. Also, we’ve already seen that you can add and subtract numbers from strings and get confusing results.

With idiomatic JavaScript, it is almost always better to use the triple equals operator === then the double equals operator ==. The double equals operator will automatically change the type of the compared variables to a similar type before making the comparison. It’s much more safe to use the triple equals operator when making a comparison.

Functions and Control Flow

When you write a function with arguments or call a function that is expecting arguments, always pass the correct number of arguments to the function. If you do not pass an argument to a function that is expecting one, JavaScript will automatically pass undefined to the function. Undefined values can often break the code. It is idiomatic JavaScript to assign default values to arguments for your functions.

When writing a switch statement you can ignore writing a default case but in doing so can easily create errors. It is more idiomatic JavaScript to write a default case even if you don’t think the switch statement will need one. Ignoring a default case in your switch statement can break your entire code base if some unexpected fringe event were to happen.

Increasing Performance

idiomatic JavaScript with ReactAccessing the DOM is extremely slow in JavaScript. Many different libraries and frameworks have been created to either speed up the DOM or create an artificial “shadow DOM”. React.js is a good example of this. React.js uses a “Shadow DOM” to allow the programmer to gain access to the DOM as many times as they want without accessing the real DOM. You are able to create HTML components inside of the JavaScript code which significantly speeds up performance.

The Todo application example that we covered a few posts back is very inefficient code. This is mainly because of how many times it accesses the DOM. If we were to rewrite the code using a library or framework like React.js, we could create the entire Todo front end inside of our code instead binding the input box and buttons to the JavaScript through DOM query methods. Then we would be able to render the buttons and input box all as one single component inside of the HTML. This not only decreases the page load speed but also would increase the rendering speed.

Conclusion

In this post, we talked about idiomatic JavaScript. We discussed various different rules which should be followed for efficiency and to avoid needless errors. We also talked about increasing the overall performance of our code and touched on the advantages of using a shadow DOM. In our next post, we will start to look at a more advanced piece of JavaScript.

JavaScript Object Notation

In the last post, we took a look at a Todo application. Our Todo app was very simple and it has no means to store data. To be able to store data we need to learn to use JSON. In this post, we are going to talk about the JavaScript Object Notation or JSON for short.

What is JSON? JSON or the JavaScript Object Notation is a way for us to store information in an organized and easy to access manner. Quite simply, it gives us a method of storing data in a readable format that is also very logical as well. From the name, JavaScript Object Notation, we can infer that this method relies heavily on JavaScript Objects. Here is a simple example in JSON format.

We’ve created an object here that we can access with the variable person. We’ve used the object literal notation to define the variable as an object. Inside of this object, we can have any number of "name" : "value” pairs separated by commas. When we want to access the date inside of this object we can simply refer to the name of the property we need using the standard “dot syntax”.

Nested Arrays and Objects

We can also store more objects into one single variable by taking advantage of arrays. For example, if we want to have two Person objects in one variable expression we can simply enclose them in square brackets and separate the two objects with a comma. Another way to store multiple people in one variable is through the use of nested object notation. Here is an example of both.

Using nested objects to store data makes use of much easier to understand syntax than using arrays. As you can see, we just simply use the dot syntax and call the outer object name, the inner object name then the property name that we wish to access.

The great thing about JSON or the JavaScript Object Notation is that it is lightweight and also is very readable. It also makes use of the JavaScript language which we are currently working with. We don’t have to import SQL or another database language to give our applications a backend. While this is true, it is worth noting that JSON isn’t all technically JavaScript. JSON just happens to be syntactically identical to the code for creating JavaScript Objects.

Language Independence

JavaScript Object NotationJSON the JavaScript Object Notation typically is defined in its own file, a .json file. If you build a node application, you will use JSON to store your dependencies and project information. Also, because of it’s easy of use, JSON is used as a language independent way to store data for applications. This means, that you will often see JSON in Ruby, Python, Perl, and PhP applications to name a few examples. The standard boilerplate node package.json file looks something like this.

Closing

Today, we took a brief look at JSON or the JavaScript Object Notation. We talked about how to create JSON, what it is used for and why it is useful. In our up and coming tutorials, we will look at some more advanced JavaScript techniques through the use of examples.

Programming in JavaScript: Todo App

In this post, we will now take the tools that we installed in the last post and put them to good use. We will also draw upon all of the knowledge that we have built up until now to create this “todo” application. It has become rather common in programming for people to make a todo application as their first application. It’s so common that the todo app has almost replaced the “Hello World” app as the first app people make.
todo appThe basic function of a todo application is to create a list of items that we want “to do” or have “to do”. We can add as many “todos” as we want to this list and we can cross them off the list by hitting a remove button which is right next to each element. We also have a button which will remove all of the items on the list if we wish to clear our “todos” for the day.

In our code example, we will show both the HTML and the JavaScript as one large code container then we will split it into parts and talk about what they do. Note, you can run this application by simply opening the HTML file in a browser, you don’t need to use Node.js.

The Todo Application

In this example, we have the JavaScript embedded inside of the HTML. We will ignore the HTML and talk about the JavaScript as this tutorial assumes you have a basic understanding of HTML.

Let us focus on the first few lines of the JavaScript.

This first statement is a variable declaration and binding. We are using some of the Dom methods to bind elements of the HTML to variables in the JavaScript. The method document.getElementById('list') is selecting the unordered list with the id of ‘list’. The next two statements are getting the two button elements and binding them to variables. Our next lines of code are where many of the more important parts of this program take place.

Our Main Code Logic

First, we create an onclick function called addLi and bind it to the add button. Our onclick function resides inside of an anonymous function which is then bound to our add variable’s attribute of onclick. We are making an object out of the add variable and we use an anonymous function so that add.onclick will run when we click the add button.

jscriptThe first lines of the addLi function are again variable declarations and assignments. The first one invokes the document.getElementById('text').value method to get the string from the input box. Our li variable is bound to a function which creates a new li list element, document.createElement('li'). The textNode variable calls the document.createTextNode(inputText + " ") method to “mount” the text from the input box to the new li list element. Our final variable declaration removeButton creates a button that will be mounted onto the new li list elements.

The next line is a call to allow us to clear the text input by setting it equal to an empty string with document.getElementById('text').value = ''. We then enter an if statement which checks to see if there was indeed an input into the input box. If there is no input, the program deploys an alert box to the screen and returns false. If the if statement passes we go on to the next lines.

The lines after the if statement are lines to create the removeButton element which is mounted in the li list elements. We are creating an object out of removeButton which has two properties; className and innerHtml; and an onclick method; removeMe. The className property gives the button a class name of "removeMe" and the innerHtml property gives the button a label of " DONE!".

The final three lines in this function mount the text node and button we just created onto the list element using the appendChild method. We then call the appendChild method on the unordered list that was passed to the function, targetUl. Let us now turn our focus to our final lines of code.

Adding Logic to the Remove Buttons

We create a function removeMe, which is the function that is called as an onclick event on the removeButton we just made. First, this function selects the parent HTML element of the button itself which is the li list item by using the parentElement method. The function then calls the parentElement of the li list item which is the unordered list and deletes that li list item using removeChild(self). Keep in mind that the parent variable is bound to the original list item that has the button we just clicked on.

The final function in this code is an on click method for the removeAll button. This function removes all of the li list items by setting the inner HTML of the unordered list equal to an empty string.

Closing

In this post, we took a look at an inline HTML vanilla todo application. We talked about how the JavaScript works line by line. We also looked at various methods that we can use to target HTML elements and their properties. If you want to see a video version of this post, go to our vanilla todo app video tutorial. If you would like to brush up on your HTML knowledge, we recommend checking out w3school’s tutorials. You can download a version of this code with styling at our github repository.

Setup A JavaScript Environment

In this post, we are going to talk about how you can setup and deploy a JavaScript environment on your own computer. We will talk about installing Node.js, using the Node package manager (npm) and installing various different text editors and IDEs (integrated development environments).

Our tutorial is approaching the point where we will start to look at real world code. While you can use some of the online editors that we talked about in our first post; having an offline JavaScript environment is also beneficial. Learning to use Node.js is also extremely important for anyone who wants to seriously get into programming (even if you don’t plan to use JavaScript).

Installing Node.js

NodeJS JavaScript environmentOn all three operating systems, you can get Node.js by going to their website. When you get to the website you will see two versions that you can download, the LTS version and the latest release. The LTS (long term Support) version is the one you want in 99% of cases. It is worth noting that at the time of this post, Node.js is actually rolling their LTS onto version 6.9.0 and will be stopping their support for version 4.6.x as of April 2017.  We recommend that you get Node 6.9.0 because it will be supported longer.

On Windows, you will get a .msi installer. Just follow the installation instructions to install Node.js. On Mac, you will get a .PKG file which you can run to install Node.js. On Linux, you can get the tar.xz file which you can unzip onto your system or you can check your package manager for a build of Node.js (most have it natively). When the installation finishes, open up a terminal or command prompt and type node --version and npm --version. Doing this will verify that both NPM and Node are in your path and are installed properly.

Picking a Text Editor

There are various different text editors and Integrated development environments that you can choose from for programming in JavaScript. The first is GNU Emacs which is a text editor that has been around for almost 30 years now. Emacs has a very steep learning curve but its extremely powerful once you’ve mastered it. You can use Emacs for any type of development imaginable and even run it as a window manager on Linux. Emacs features a set of powerful keyboard shortcuts and it’s own package manager.

vimAnother old and very powerful option is the VIM editor. Vim is about 25 years old and also has a steep learning curve. Vim’s keyboard shortcuts are so powerful that many other text editors have had Vim modes created for them. Vim features powerful keyboard shortcuts and its own package manager.

sublime_text_logoThe next text editor that is worth noting is Sublime text. Sublime text is relatively new compared to Vim and Emacs. Sublime text is very lightweight and hackable. This makes it a very strong choice for anyone who just wants a quick and easily solution. Sublime text does have a package manager but you need to follow a few steps to gain access to it.

The other Text editors worth noting are the Atom text editor which was created by Github, the Brackets text editor which was created by adobe, the Visual Studio Code text editor which was created by Microsoft and the Notepad++ text editor. All of these editors have package managers and can be installed on any operating system. They all have their various pros and cons which we go over in our video about picking a text editor. If you don’t feel like installing multiple packages on a text editor and want something more robust, then installing an Integrated Development Environment is the choice for you.

Picking an IDE

IDEs usually support a specific set of languages though there are many that also have extensible systems. The main advantages of an IDE are that most of the features work out of the box and they tend to be very straightforward. For JavaScript, you have various different IDEs to choose from.

intellijThe first one that we will mention is the IntelliJ Webstorm IDE. While Webstorm is technically not free, you can try it out for 30 days and if you have a .edu email address you can get a one-year license to all of the IntelliJ IDEs for free. The IntelliJ IDEs are extremely powerful and have many different features. You can also use the standard IntelliJ Idea Ide for JavaScript development using various plugins. IntelliJ is the company that powers the official Android Studio IDE.

eclipseThe next IDE that is worth talking about is the Eclipse IDE. Eclipse is a fully open source project and as such, there are various different flavors that you can download. The JavaScript flavor is extremely powerful and hackable. Eclipse also has a fierce community following which is what drives the support of all of the plugins. Eclipse is relatively compact compared to other IDEs and as a result, it can be a good choice for an older machine.

visual-studioThe last IDE that we will mention specifically is the Visual Studio IDE. Visual Studio is a Microsoft product and until recently, it was a Windows only IDE. Visual Studio Community is an extremely powerful IDE with first-class support for the .Net languages such as C#, C++, F# and Visual Basic. It also features first-class support for TypeScript and JavaScript. Visual Studio is a very powerful tool set that is worth looking at if you really want something heavy.

Which Should I Choose?

Choosing a JavaScript environment is an extremely important decision. If you decide to put in the effort, learning more complicated code editors like Emacs and Vim can really pay off in spades. If you are just approaching programming as a hobby then some of the lighter code editors might be the right choice for you. We recommend that everyone should try all of the text editors and IDEs that we’ve listed to find the one that suits you the best. Of course, there is no reason why you can’t use multiple coding environments. If you are just starting out it is recommended that you choose one environment and master it before moving on to another.

One more technology that should be noted is Docker. Docker allows you to deploy a “container” on your machine which can be easily moved around and redeployed. Learning how to use Docker is something that is worth exploring if you do not want to mess with your operating system by installing Node.js and a text editor. It is also worth looking into if you are using a setup that is not very common.

Conclusion

In this post, we talked about how to setup a JavaScript environment on your computer. We talked about Node.js, Text editors and Integrated Development Environments. We also briefly touched on the Docker technology. In our next post, we will start looking at real world code examples by looking at a very simple “Todo” application.

Errors and Exceptions in JavaScript

In this post, we are going to look at errors and exceptions in JavaScript. Errors and bugs will happen even to the most careful programmer. They mainly happen due to a direct error that the programmer makes or because the program does something that wasn’t accounted for. luckily, JavaScript features some in-code tools to help us debug these problems.

Try-Catch Statements

The main in-code method that JavaScript has to handle errors is called a try-catch statement. The try-catch statement is a type of control flow statement in which the catch block will only execute if an error is thrown in the try block. In other words, the try block is where the code we want to test resides. The catch block is a block of code which will be executed if the try block throws an exception.

Here we have a pseudo-code version of a try catch block. The try block throws an error, e which is passed into the catch block like a variable. We can pass a variable into catch because when JavaScript code raises an exception it generates a message. We can use the throw statement to manually throw our own exceptions in JavaScript. The throw statement can take a type of String, Number, Boolean or Object.

The main reason why the try-catch statement is so powerful is because it is hard to tell what a user will do when they are accessing your program. One of the more common uses for a try-catch block is for form validation. You can’t control what a user will put into your input text boxes but you can restrict what inputs are valid in these boxes.

Using Debuggers in JavaScript

errorThe other main resource used for dealing with bugs in JavaScript is a debugger. The debugger allows you to set breakpoints in your JavaScript code to see what “state” the code is in at a given moment. Natively in JavaScript, there is a keyword debugger which will stop the execution of the code and send a call to a debugging function. This is basically like setting a breakpoint in the browser, except you manually are typing it into your code. If you try typing debugger into your JavaScript console, it should bring up your browser’s native debugger window.

In most browsers, your debug window is actually your JavaScript console or an extension of the JavaScript console. It is actually quite common for programmers to use the console.log() function for debugging as well. You may notice that upon opening the console in certain URLs you will see error codes. These are mostly from broken JavaScript on the page you are viewing or from an extension you have installed on your browser.

Closing

Though this post was much shorter than normal, we covered error exceptions in JavaScript and exception handling in JavaScript. We looked at the throw statement, the try-catch statement and we looked at the debugger keyword. We also talked about setting breakpoints and looking at state.

In our next post, we will start to look at a simple real world example of JavaScript.

 

Regular Expressions in JavaScript

In our last post, we went over some of the smaller features that we skipped over in this tutorial. In this post, we will be looking at Regular Expressions in JavaScript or regex for short. Regular expressions are an important part of any language and JavaScript is no exception.

Writing RegEx

Regular expressions are patterns of characters that are used to match character combinations in strings. Regular expressions are objects in JavaScript and you will often see them in form verification applications. There are two ways to create a new regular expression in JavaScript; you can use a literal format or a constructor.

A regular expression literal is surrounded by backslashes /, which are the escape characters in JavaScript. Here is an example of a regex literal.

The regular expression constructor format follows the pattern of all other constructors in JavaScript. You use the new keyword followed by RegExp. Typically, you will use a constructor when you know that the pattern will be changing or when you might be getting the regex pattern from another source. Here is an example of a regex constructor.

RegEx Characters

long-regexRegular expressions composed of simple characters are used for direct matching. Keep in mind that regex are case sensitive by default. For example, a regex of /dog/ will only match strings with the characters “dog” in them. The characters must also be in the original order, “dog”.  The string “let us walk the dog” will match with this regex, but a string like “dinosaurs of Georgia” will not match even though it contains the “dog” characters.

When you need to go further than a direct match you can use special characters as well. For example, the regex /ea*t/ will match with any character combination where a single “e” is followed by zero or more “a”s which is immediately followed by a “t”.  To find out what all of the special characters do look at the Debugex cheatsheet here.

RegEx Methods

Like any other object in JavaScript, Regular expressions have their own methods. Here are some of them in action.

The exec method applies the regex to the given string then returns an array of the match information. The test method looks for a match then returns true or false. The match method returns an array with the first matched string and all matches if you pass the global flag. The search method returns the first index value of the match and -1 if there is no match. The replace method matches the regex then replaces the match with the second argument. The split method matches the regex then splits the string into an array at the matches.

RegEx Flags

Regular expressions also have what are called flags. There are three flags which are used in JavaScript regular expressions; g, i and m. When you create a regular expression literal, the format follows, /pattern/flags; The constructor has a pattern like this, new RegExp('pattern", "flags"); You many pass multiple flags at once. The global flag g makes the regular expression match the entire string and creates an array of the match occurrences. The ignore case flag i makes the regular expression case insensitive. The multi-line input m flag makes the beginning of input character ^ and the end of input character $ apply to both the beginning and end of input. The last flag is not used as much and is only supported by JavaScript version 1.5 and above.

Closing

In this post, we looked at regular expressions in JavaScript. We talked about the methods that come with regular expressions and the various characters and flags that can be used in them. Our next post will look at exception handling and we will start to move into real world examples.

Filling in the Holes

In this post, we are going to go over some of the topics that we glossed over in our main tutorial. There are a few important topics that we didn’t fully cover when going through the core language. Before we start to look at real examples of programs, we need to fill in the gaps of our knowledge.

The Ternary Operator

The first topic that we need to look it is called the ternary operator. The ternary operator is a type of conditional. It follows this pattern: condition ? true : false. The basic idea is that the ternary operator is shorthand for an if statement. Here are some examples.

ternary-operatorThe ternary operator is a quick way to determine if a condition is true or false and a shortcut for allowing you to simply execute code based on the condition. You can assign a ternary expression to a variable like you would with a function. This assigns the “return” value of the ternary operator to the variable. The return value being the last line of each expression. In our example, the value of t will be true or false depending on the value of x.

And, Or, and Not

The next set of concepts that we need to look at are the logical operators && and, || or, and ! not. These logical operators allow us to make complex conditionals. Take a look at the logic table below.

booleanoperatorsThese can be used for complex conditional statements but make sure to use the correct conditional symbols for your statements. If you have code that should run if only both statements are true then you use an “and” conditional. If you are using multiple if statements, you might find that you can combine them with one of these operators.

The Continue Keyword

continueThe last concept that we will look at today is the continue keyword. We talked briefly about the break keyword when we looked at switch statements. The continue keyword tells the program to continue a loop rather than break completely out of it. However, the continue keyword is still a “break point” keyword. This means that when the loop hits a continue keyword, the code will go back up to the top of the loop and start with the next loop iteration. Look at the example below.

In this example, because of the continue keyword and the if statement, the code will not print out any even integers in the loop. The break keyword ends the loop at 15 rather than at 20, and so the console doesn’t print out 15.

Closing

Before we dive deep into real word programming examples, we still need to cover two larger concepts. The first concept is exception handling and the final concept will be regular expressions.

In this post, we looked at the ternary operator, the and/or/not logical operators and the continue keyword. In our next posts, we will look at exception handling and regular expressions.

Classes in JavaScript

In today’s post, we are going to look at the class system in JavaScript. The class system in JavaScript is a little different when compared with the class systems in other object oriented languages. More specifically, the way that inheritance works in JavaScript is a bit different from most object-oriented languages.

Prototypical Objects

Object PrototypeAs we’ve already mentioned, Objects in JavaScript are based on a prototype system. This means that every object or instantiated piece of data in JavaScript has built-in inheritance. When you create an array, the array has the properties of the Array.prototype and Object.prototype prototype as well. You always inherit the Object.prototype prototype when you instantiate a new piece of data that isn’t a primitive. The Object.prototype prototype is always at the top end of the prototype chain of inheritance.

This is an important concept for classes in JavaScript. Prior to the introduction of the class keyword in ES6, to create inheritance in JavaScript you mainly accessed the prototype and prototype chain. In other languages like C++ and Python, instance objects and classes are separate concepts. Classes in JavaScript, due to the prototype chain, are not.

Classes as a Feature

Classes in JavaScript are a feature that was introduced into JavaScript as a syntactic sugar in ES6. They still make use of the prototype system but the added syntax is much more simple and convenient by comparison.  Let’s take a look at a simple example.

In these examples, we created two animal classes, one using the new class syntax and the other using the old prototype syntax. Now, let us look at adding inheritance to another class using the ES6 syntax.

es6In the example above, we create an Animal class then use that Animal class as a template for our Dog class. The Dog class inherits all of the properties of the Animal class including the speak function but we override that function with our own version specifically made for the Dog class. We can override a class property by creating a new one using the same name. We can also create a new property with the same name and call the original property with the keyword super. The super keyword is like the this keyword except it refers to the parent or super class rather than the class object that we are inside of.

As you can see, the lion example modifies the speak function rather than completely replacing it. The modified speak function has the original call in it and a new console.log(); statement. Every time we invoke speak() on an instantiated Lion class object, we will invoke the Cat.speak() function as well.

Class Expressions

Because the class keyword works like the function keyword we can make “anonymous” classes or class expressions.

In our first class, we create a class expression on the variable Square. We still need to use the new variable to call this Square variable and to call our Square2 class. Class expressions usually are used like callback functions, as arguments for functions or other classes.

As you’ve probably noticed, we use a function inside of our class called constructor when we create a class. This constructor function is a keyword for creating and initializing an object created by the class. Basically, the constructor function is called when we instantiate any of these classes into objects. Like any other keyword, the word constructor can not be used for a function name so you can’t make multiple constructor functions inside of a class. You may, however, use the super keyword instead of this inside of the constructor class to access a parent class’ constructor variables if you extending one.

Closing

Today we introduced classes in JavaScript and their basic properties. We talked about the ES6 syntax and the constructor method as well as class expressions in JavaScript. We also touched on the Prototype Chain method of creating classes and inheritance.

In our next post, we will start to look at a practical example so that we might fill out our core knowledge of JavaScript.

 

Self-Invoking and Anonymous Functions in JavaScript

Functions are used in many different areas of JavaScript. Functions in JavaScript are a powerful way of freezing code for further use. Thus far, we used different functions to define object constructors and object behavior. In this post, we are going to look at some of the other ways that we can take advantage of functions in JavaScript.

Anonymous Functions in JavaScript

anonymous functionIn JavaScript, a typical function declaration utilizes the function keyword followed by the name of the function. We name our functions when we want to invoke them multiple different times in a piece of code. Sometimes, we want to be able to pass a function directly to another function as an argument. We were actually doing something like this when we were defining our getter and setter functions in our last post. The get: and set: keywords are both function shortcuts.

Most of the functions we’ve been writing inside of objects are called anonymous functions. Anonymous functions are functions that are not defined with a name. Typically, these functions are used for one of three main reasons.

The first way they are used is for direct variable definitions. This style of anonymous function is the most like a normal function declaration in that it is bound to a variable name. It can be invoked by calling that variable as an execution (with parenthesis). This is the type of anonymous function you will most commonly see inside of objects and constructors as well.

These are not the most realistic examples but they work for our purposes. These shaky examples just simply show that you can substitute a return value for a variable declaration in most cases. The second example displays a concept called side-effecting which we will talk about at length in a future post (the console.log() is the side-effect).

Callback Functions

Another common way that anonymous functions are used in JavaScript is as arguments for other functions.

callback anonymous functionsThe setTimeout() function is a very good example for this type of use. The first parameter that we pass to it is a function we want to run. The second parameter is the amount of milliseconds that we want to pass before this function runs. In this example, we’ve specified 3 secs or 3000 milliseconds before this anonymous function runs. You will see this type of anonymous function used many times when working with web applications. Typically, we call these functions callback functions.

Before we get to the last most common method of using anonymous functions, we need to define self-invoking functions.

Self-Invoking Functions

A self-invoking function is actually an anonymous function itself. A self-invoking function automatically runs on its creation and can only be run once. Here is the general format for this type of function.

self-invoking functionsFunctions run immediately in JavaScript when you place a set of parathesis after their names. This is an important thing to remember because in JavaScript you only put semicolons after execution statements. You may have noticed that after a function declaration you don’t put a semicolon. This is because the code is being stored for later. With self-invoking functions, however, we are not storing any code for later use. We are running the function right then and there.

The main reason to use a self-invoking function is for data privacy. Self-invoking functions are primarily used to create what is called a closure. A closure is a method of creating private variables inside of a function block. Closures can be used to create variables that act like the block scoped variables created by let as well. Closures are our last main use case for anonymous functions.

Closures

In JavaScript, functions have access to global variables and to variables defined inside of them. This can be a problem, for example, in web development, the global variables belong to the window object. Any script running on the page can actually access and manipulate any of these global variables. Look at this classic example.

With these examples, we can’t increment the count variable past one because every time we call the functions, we reset the count variable to zero. If we use a closure, however, this problem is easily solved.

closure-introIn this example, we set the add variable to the return value of a self-invoking function. This means that the outer function only runs one time, which sets counter to zero. The inner function works like a normal anonymous function. After the outer function runs from the declaration, when we call add(), only the inner function runs. In this example, the scope of counter is only inside of the self-invoking function and the add function. This means that after the self-invoking function runs, the add function is the only function that can touch it.

Closing

In this post, we took a look at the primary use cases for anonymous functions, for variable definitions, for callback functions and for creating closures. We also looked at self-invoking functions and how JavaScript scope can sometimes work against us.

In our next post, we will start to look at classes in JavaScript. As always, feel free to leave a comment if you thought we left anything out or if you need more clarification.