TagJavaScript Console

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.

 

Loops inside of JavaScript

Loops are a very important part of programming.  In video games, the core logic is a loop called the game loop.  You make a choice, the game logic reacts, and then updates the screen with the next set of choices. This loop continues until you either win the game, lose the game or hit a fail state. In JavaScript, loops are important because they allow you to iterate over data quickly and efficiently. Larger data structures like Arrays and Objects are easier to read when you use a loop.

For Loops in JavaScript

The most used loop in JavaScript is the For loop.  A typical For loop looks like this:

The for loop uses an inbuilt variable to help iterate over whatever code you are trying to run. You can use a variable definition outside of the for block as an iterator but it is not exactly idiomatic to do this. Here is an example of what a for loop would look in a real piece of code:

for-loopIf you run this block of code inside of your JavaScript console you will see that the words "i times!" will be printed to the console 10 times with i iterating upwards from 1 to 10. You might also notice that the iterator i does not need to be defined as a variable because the for loop automatically reads it as one.

The console.log() part of this code block is a function that prints whatever is inside of the parathesis to the JavaScript console, in this case, the variable i concatenated with the word " times!".

While Looping in JavaScript

Another common type of loop is a while loop. A while loop continues to loop while the conditional statement embedded inside of it remains to be true. The general structure of a while loop looks like this:

Here is an example of a while loop iterating over a block of code:

while-loopNotice that the while loop features the iterator variable inside of its body rather than inside of the conditional statement like the for loop. This also means that before running this block of code you must define the iterator variable outside of the while loop. The main reason for this is because iterator variables are rarely used inside of while loops like they are in for loops. While loops are more commonly used for boolean type operators where an item is either true or false.

This is also a good time to bring up the iteration operator again. As you’ve probably noticed in both loops, the iteration of the variable in the conditional has been handled with a short-hand notation ++. This plus-plus sign adds one to the variable each time it is run.  Similarly, you can subtract one from a variable using minus-minus -- as a shorthand operator. Be careful where you put the iterator operator in relation to the variable, putting the operator after is called post-iteration and putting it before is called pre-iteration.

++i will increment the value of i, and then return the incremented value, so if you run this code for example:

If you use pre-iteration in a for loop you can sometimes accidentally skip a number unless you take steps to deal with how the variable is treated.

Conclusion

In this post, we talked about looping in JavaScript, mainly for and while loops. We also spoke briefly about the console.log() function and the different shorthand methods of iteration. In our next post, we will talk about Arrays. As always, if there is anything you think we left out or you want to talk about please comment below.

Beginning with JavaScript

dev-consoleJavaScript is compact in that unlike many other programming languages, you don’t have to install a compiler or an interpreter to get it working. If you are running a web browser then you can already access a JavaScript console without installing anything else. In the case of Google Chrome and Mozilla Firebox simply pushing “control+shift+I” will bring up the developer tools panel (for windows Internet Explorer or Windows Edge, just push f12 or “control+2”). Each set of developer tools has a tab labeled console which allows you to write and execute JavaScript code. You may also use some of the other tabs to do other cool and useful things but we will leave them alone for now.

cloud9If you wish to develop in JavaScript past simply writing small pieces of code inside of your browser you also have many different online and offline options to choose from.   JS Bin, JSFiddle, and CodePen are some of the more popular online options. You may also choose one of the more fully featured cloud IDEs (integrated development environment) like Cloud9, Codenvy or CodeAnywhere.

If you want to develop JavaScript offline, then installing Node.JS and NPM (Node Package Manager) is a must these days. Node.Js gives you access to a server which will let you run your code. It also lets you access a metric ton of cool JavaScript frameworks, libraries, and development tools.

If you are looking to code along with this blog, I would recommend either finding a cloud IDE that you like or installing Node.js for your platform; click here to find the instructions for your operating system.  For Windows machines, you can use Chocolatey as a package manager or install Node through the executable found here. (Note: I recommend using Chocolatey because it sets up your PATH variables for you and you gain access to many different packages.)  You won’t really need Node or NPM to follow these tutorials (at least until we say so), most basic JavaScript work can be done through a browser console or by using something lightweight like CodePen or JSFiddle. You can also take a look at some of the offline options that we recommend here.

Let’s Start with Some Basic Coding!

JavaScipt is a Dynamic, Untyped, and Interpreted language with both Object-Oriented and Functional Programming paradigms baked into it.  As you read through our blog postings you will start to learn what some of this stuff means, but for right now its probably best just focus on the “Interpreted” part.

An interpreted language is a language which does not need to be compiled down to bytecode before being run.  The JavaScript Interpreter “translates” the code line by line at runtime rather than beforehand.  This is what allows for the JavaScript Console to work the way it does.  If I open up my JavaScript console and type something such as var x = "Hello, World!" then press the enter key, the console will spit back undefined. The reason we see undefined rather than "Hello, World!" is because assigning a variable has no return value (This isn’t important yet, just keep it in mind). In this really simple case, we are assigning the string Hello, World" to the variable x and the console is spitting back the return value of running a variable definition undefined.

If we type in just the string portion "Hello, World!", the console will spit back 'Hello, World!' and if we just enter x into the console we will now receive the string "Hello, World!" as well. What we’ve done is assign the value of the string "Hello, World!" to the variable x. The assignment of x can be changed (is mutable) and has a lifetime as long as the window or tab is open (once you close the window the console will clear all variable assignments.) You may also simply refresh your page to clear your data assignments from the console.

Closing

In this post, we wrote a fairly basic “program” which assigns a string to a variable. In our next post, we will go over the different types of data that can be assigned to variables in JavaScript, why it’s called an “untyped” language and some of the different ways that we can manipulate this data.