≡ Menu

Debugging in JavaScript

Every programming language that you’ll use will have some sort of tool that allows you to debug the code you write.

Without debugging, finding the errors in your code would be VERY time consuming.

The magic of using a debugging tool is that it allows you to run your code line-by-line at a pace that you’re comfortable with. This means that the computer won’t just FLY through every single line of code and leave you guessing what the heck just happened. Debugging tools will allow you to dissect and inspect every single aspect of your code as it’s running.

This is massively useful, as it allows you to spot any potential errors/bugs in a much more human way.

What Tools to Use to Debug in JavaScript

JavaScript is a bit unique as it exists in the browser that you use. So the tools that enable debugging in JavaScript will be different depending on which browser you use.

As I’ve mentioned before, I would recommend you use either the Google Chrome browser or Mozilla’s Firefox browser.

Debugging in Chrome

If you’re using Google Chrome, then you’ve already got the debugging tool built right into your browser, just hit the F12 key (or CMD + OPT + I on a Mac) and you’ll see it pop up.

In Google Chrome, it’s called the developer tools window and it actually gives you more than just the ability to debug your JavaScript code. It also allows you to inspect pretty much any aspect of any webpage you visit. But to stay on topic, I’ll only talk about debugging.

I’ve actually done something special for this tutorial and I’ve included a JavaScript file, which you will be able to use as a debugging example. Aren’t I so thoughtful? This will make it easier to explain the steps involved in debugging.

So, to start debugging the JavaScript file I’ve included in this blog post, follow these steps:

  1. If it’s not already open, hit F12 (or CMD + OPT + I on a Mac) to open the Dev ToolsDebugging In JavaScript Step 1
  2. Click on the Sources TabDebugging In JavaScript Step 2
  3. Navigate to the “Debugging_Example.js” file via the “wp-content/uploads/2015/07” folder and click on the JS fileDebugging In JavaScript Step 3
  4. Notice that it opens a “Debugging_Example.js” tab in the main windowDebugging In JavaScript Step 4
  5. Now click on any of the line numbers (on the left side) to add a breakpoint. This is where the code will “pause” so you can debug line by line.Debugging In JavaScript Step 5
  6. Then you’ll need to refresh the page to start the debugging process.
  7. Once the page refreshes, you’ll see that it will “pause” at the breakpoint that you previously inserted. Debugging In JavaScript Step 6
  8. Now you can step through the code line-by-line using the “Step Over” icon in the top right of the Dev Tool.Debugging In JavaScript Step 7

As you step through the code line by line, you’ll see that the console messages will appear right when you hit the “step over” icon. Plus you’ll get to see exactly how the for loop iterates over your code.

Debugging is not only a handy tool, but it can also serve as an educational tool for learning how the code functions as it’s being run.

Debugging in Firefox

Firefox uses a plugin called “Firebug” that will need to be installed. It’s very similar to Google Chrome’s Developer Tools. To download Firebug, go to this link: https://addons.mozilla.org/en-us/firefox/addon/firebug/, or if that link happens to be dead then just Google “Firefox Firebug” and you’ll be sure to find a working link to install the plugin.

Once you’ve installed the plugin, you can launch it in the same way that you launch the Google Dev Tools, by hitting F12 (or CMD + OPT + I on a Mac).

The beauty about the Developer Tools / Firebug plugin is that they both function in nearly identical ways.

To debug your code using the Firebug plugin in Firefox, just follow the same steps that we’ve outlined above in the “Debugging in Chrome” section!

{ 1 comment }

Functions in JavaScript

Functions in any programming language are almost as important as having variables. So that should go without saying that functions are hugely important to understand and to use in the JavaScript language.
Functions in JavaScript
Functions are what allow us to re-use code, and organize the functionality of our programs into neat little packages.

That’s really all they were created for. To organize the functionality of our code, and to allow us to re-use that code over and over again by “invoking” or “calling” the function.

So let’s start things off by asking the following question: “What do you mean by organizing the functionality of your code?”

The first thing I’ll point out is, look at the word “functionality”, isn’t it interesting that it contains the word “function”?

Oh snap!

By functionality, I mean the actions that our programs perform.

Let’s say we’re looking to create a number guessing game. The computer will pick a random number between 1 and 100, and we are tasked with guessing what number the computer has picked. We have 5 guesses, and each time we guess, the computer will tell us if we need to guess higher, or lower.

Okay, cool, so we have an idea of how this game should work, now how would we outline the “actions” that this program should perform? In other words, how do we outline the functions that will exist?

Well the way I would do it is I would think about all the steps that would need to happen in order to carry out this task in real life. It might look something like this:

  1. The computer will need to randomly pick a number between 1 and 100
  2. I would then hazard a guess at what number they picked, say, 50
  3. The computer would tell me if I am right, or if I need to guess higher, or lower
  4. I would then make my second attempt at guessing the number (let’s assume I needed to guess higher), so I would choose 75
  5. The computer would tell me if I am right, or if I need to guess higher, or lower
  6. I would then make my third attempt at guessing the number (let’s assume I needed to guess higher), so I would choose 85
  7. The computer would tell me if I am right, or if I need to guess higher, or lower
  8. This would repeat until I either guessed right, or I used up all my attempts

When you write out all of the steps, you can quickly see where some of the steps are similar based on how they repeat.

For example, I can see that the computer always needs to check if I was right, or if I need to guess higher, or lower. This is essentially an action that’s performed MANY times by the computer… so this would be a perfect candidate for a function.

The second thing that happens often, is that *I* would attempt to guess a number, so that could be a function as well.

And finally, there’s that bit at the beginning that only happens once, which is where the computer needs to pick a random number. What I would do here is just realize that this is something that happens when we START a game… or perhaps more specifically, something we do when we want to start a NEW game. So if we want to be able to play MANY games in a row, this could become a function as well, as we would need to invoke this many times.

So, we’ve outlined three functions, all we need to do is give them names.

That’s right, functions need names, it makes the code more “human readable”, which is a good thing 😉

Syntax for Functions in JavaScript

Let’s talk syntax.

If you’ve got a Java programming background, this syntax will look slightly different. There’s a specific reason why it’s different though, and that’s because JavaScript has dynamic types, so there’s no need to specify a type in the function.

Here’s a general outline of a function’s syntax in JavaScript:

function myFunction (param1, param2, param3)
{
  // insert relevant code here
}

In the example above you’ll notice that I have three parameters being “passed into” the function. This is just an example, and you can feel free to pass in ZERO parameters, or more.

The process of “passing parameters” into a function is very common in modern day programming languages. What’s happening here is that the function is saying “Hey, I need certain parameters to be given to me in order for me to do my job correctly.” If you don’t give a function what it wants, meaning, if you don’t pass it the right number of parameters (whether that’s none, one, two, three, or more) then the JavaScript engine will complain.

In the case of my generic example above, we have no concept of what the parameters mean or what they do, as it’s just a generic example.

Here’s an example of a generic function that doesn’t require any parameters:

function anotherFunction ()
{
  // insert relevant code here
}

Voila, another function that this time doesn’t require any parameters.

Alright let’s talk real world examples now…

Functions for the Number Guessing Game

Let’s break down what one of the functions would look like in our game. Let’s use the function that verifies if the user has correctly guessed the randomly selected number. Before we just into the code, we’ll need to make an assumption that somewhere above the code we’re about to see, there’s a variable that’s been declared that holds the number we wish to guess. Let’s call this variable numberToGuess.

Okay great, let’s see the function:

function isNumberHigherOrLower (usersGuessedNumber)
{
  if (usersGuessedNumber == numberToGuess)
  {
    return "Correct";
  }
  else if (usersGuessedNumber > numberToGuess)
  {
    return "Lower";
  }
  else
  {
    return "Higher";
  }
}

First thing to note here is that we’ve assigned a meaningful name to the function. I decided that I wanted to call this function isNumberHigherOrLower, to me this is a pretty good name because it more or less defines what the code inside the function will be doing. If I wanted to be even more verbose, I could have named it isGuessedNumberHigherOrLowerOrCorrect, but there comes a point where super long function names just get annoying.

I’ll let you decide what your threshold is for function name length!

The second thing to note is that I’m using the return keyword.

Returning Values from Functions

Functions can do one of two things:

  1. Functions can just execute code and then allow the flow of code to exit and return back to wherever the function was originally called
  2. Functions can return data to the place that called the function

This gives functions an added layer of usefulness, because not only can they allow you to re-use code and organize your code, but they can also give you relevant data based on the specific execution of the function.

So in the example of our function, a different value is returned based on what you pass in.

This means different INPUTS lead to different OUTPUTS.

Let’s assume the number to guess is 50, based on this assumption, take a look at what our function would return based on the inputs we give it:

isNumberHigherOrLower(49); // returns "Higher"
isNumberHigherOrLower(51); // returns "Lower"
isNumberHigherOrLower(50); // returns "Correct"

You see?

We get three different outputs from the function based on what number we input into the function.

So based on the outputs, we can have our game behave in different ways.

By the way, I also just showed you how to invoke/call a function. To tell your application that you want to “use” a function’s code, you just type in the function’s name followed by an open and close parenthesis… you should also pass in any values that it needs. In the case of our isNumberHigherOrLower function, it only wants one parameter, which we named usersGuessedNumber.

It can be a bit confusing if you’ve never seen a function in action before, but I assure you, you’ll become very comfortable with them after you’ve created a handful of JavaScript programs for yourself.

In Summary

JavaScript functions are very similar to Java functions with one major difference.

JavaScript functions don’t require you to put in the parameter variable’s type in the function’s definition, this is because JavaScript uses dynamic typing, so it wouldn’t make sense to put in a type for the parameter, right?

Functions are extremely useful and without them, all programming languages would be rendered pretty much useless.

So you need to learn them and master them.

If you don’t quite “get it” yet, you’ll be seeing plenty more examples of JavaScript functions in action in the coming tutorials.

And as always, don’t forget to put your email address into our handy dandy box below to receive a free googie delivered right to your inbox. I’m pretty sure you’re gonna want to check it out… I’m kind of a big deal 😉

{ 0 comments }

While Loop in JavaScript

While Loops in JavaScriptThe while loop in JavaScript is yet another type of control structure. For a review on what a control structure is, please see our last post on IF statements.

The main goal of the while loop is to continually re-run a specific chunk of code over and over again. This is very similar to the for loop with one important difference. Again, if you aren’t familiar with the for loop, please review the topic here.

Let me take a minute to explain the difference between these two types of loops.

What’s the Difference Between a WHILE Loop and a FOR Loop?

The difference between these two loops is how they decide to STOP looping.

You see, the for loop has a specific and predefined number of iterations that it will make. We know exactly how many times a for loop will iterate once the code is running and the JavaScript engine starts executing the for loop’s code.

This is in stark contrast to the while loop. The while loop keeps looping while a specific condition is true. Once the condition evaluates to false then (and only then) will the while loop stop looping.

The reason why this is so different than the for loop is that we don’t necessarily know when this condition will change from true to false, so we can’t really guess how many iterations the while loop will make until it stops.

This is both a good thing and a bad thing.

Pros and Cons of the WHILE Loop

Let me start by addressing the only real “con” to the while loop.

It can run forever!

If you’re in a situation where your while loop keeps looping to infinity, then your program is stuck (or frozen) and you’ll need to shut down your browser to terminate the running JavaScript program. Not a very good user experience.

Having said that, an unruly while loop doesn’t typically keep on running forever, because as good programmers we always make sure that our while loop’s condition will at some point evaluate to false, right?

Right!

So the one rule you need to remember (and follow) is to always make sure that your condition will eventually evaluate to false.

Alright, having said that. The “pros” to using the while loop are quite abundant. Having a loop that will continually run until such time that a condition evaluates to false is very useful.

An example of a while loop in action would be asking a user for input again and again until they provide a valid input.

WHILE Loop Syntax

The syntax for the while loop is very straight forward.

You’ll need to be sure to use the while keyword as well as defining the condition with which the loop will run. Also, like the other control structures, the while loop defines a scope.

Here’s what the generic code looks like:

while ([condition(s)])
{
  // insert code to loop over here
}

Pretty simple right? The hardest part is to figure out what condition(s) you need to put in the while loop for it to function properly.

Remember that while the condition(s) is/are true, the loop will continue to run.

Cool, so now let’s take a look at a real world example of the while loop.

WHILE Loop Example

Let’s assume we want to prompt the user with a question. We want to ask them to enter a number between 1 and 10.

But what happens if they enter an incorrect value?

Well, we should ask them to enter the value again, and to be sure to abide by the restrictions (i.e. enter a number between 1 and 10).

This is where a for loop would fail miserably, because how are we supposed to know ahead of time how many times we should ask them for the input… right? We haven’t a clue! So in comes the while loop to save the day.

Here’s what that code could look like:

var theNumber = prompt("Please enter a number between 1 and 10.");

while (theNumber < 1 || theNumber > 10 || isNaN(theNumber))
{
  theNumber = prompt("Incorrect value entered, please enter a number between 1 and 10!");
}

alert("Great! You entered the number: " + theNumber);

What’s interesting to note about the code example above is that we have three separate conditions in the while loop.

These three conditions are theNumber < 1 || theNumber > 10 || isNaN(theNumber). What this is saying is as follows:

  • IF theNumber is less than 1, OR
  • IF theNumber is greater than 10, OR
  • IF theNumber is NOT a number, then continue looping

So, because we’re using the OR operator between each statement, this means that if ANY of the conditions are true, then the overall while loop’s condition will evaluate to true, and thus it will continue to loop.

Only in the case that ALL three conditions are false, will the overall while loop’s condition evaluate to false, and thus exit the loop.

So now, go ahead and try the code out for yourself!

In Summary

The while loop is actually the only real loop in modern day programming languages. The for loop is actually just a special kind of while loop.

This is the case because you can re-create a for loop using the while loop’s syntax… watch and learn:

var counter = 0;

while (counter < 10)
{
  counter = counter + 1;
  console.log("The counter is currently at: " + counter);
}

As you can see, this code will run exactly 10 times, no more, no less. This is exactly the same functionality as a for loop.

Neat right?

So you shouldn't be afraid to use the while loop, because without it, there would be tons of applications out there that just wouldn't work properly at all!

I hope you enjoyed this tutorial, and if you did, be sure to put in your email address in the box below to get a free goodie delivered right to your inbox.

{ 0 comments }

For Loops in JavaScript

Just like an IF statement, a FOR loop in JavaScript is another kind of control structure.
For loops in Javascript
For a review on what a control structure is, please see our last post on IF statements.

The for loop’s main purpose is to force the JavaScript engine to re-run lines of code a specific number of times. This is in contrast to the IF statement, which is used to potentially SKIP certain lines of code.

The processes of re-running lines of code over a specific number of intervals is known as iterating.

So the programming “jargon” for the for loop is to say “I’m iterating through my FOR loop”, which just means that you’re re-running the same lines of code over and over again.

What’s the Purpose of a FOR Loop?

Re-running the same lines of code over and over again may seem a bit strange to someone who is new to programming, but let me assure you, it’s incredibly useful and opens up HUGE possibilities for the creation of useful programs.

Let’s take a look at the syntax for the FOR loop in JavaScript… if you come from a Java programming background it will look very similar (with the exception of the introduction of the dynamic typing concept):

for (var i = 0; i<10; i++)
{
  // insert code to be iterated here
}

For those of you who haven't seen these for loops before, this likely looks like a bunch of random letters and symbols. But let me assure you, they all have their purposes.

Note: Java programmers, take notice that we didn't declare the variable i as an int, we just used the var keyword due to the dynamic typing.

Alright, let's take a look at a generic version of JavaScript's for loop:

for ([initialization statement]; [termination condition statement]; [iteration statement])
{
  // insert code to be iterated here
}

There are three different statements inside of a for loop:

  1. The initialization statement
  2. The termination condition statement
  3. The iteration statement

Let me break down the purpose of each of these three statements:

Statement Purpose
Initialization Used to mark the starting point of the iteration of the for loop. In most cases, you would use a variable called i and initialize it with the value of 0.
Termination Used to decide when the JavaScript engine should STOP iterating over the code in the loop and exit out of the scope of the loop.
Iteration Used to determine HOW the loop will iterate each time it starts the loop over again. Most times you will use the code i++ which is used to increment the value of the variable i (initialized in the Initialization statement) by 1.

When to Use a FOR Loop in JavaScript

Alright, so you're familiar with what a FOR loop looks like, but you might be asking yourself when you'd want to use one.

Let me answer that question with an example.

Here's some code that I use to do something stupidly simple: output the numbers 1 through 15 to the console:

console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
console.log(6);
console.log(7);
console.log(8);
console.log(9);
console.log(10);
console.log(11);
console.log(12);
console.log(13);
console.log(14);
console.log(15);

I know, I know, this is a silly program, but I'm using it to illustrate a point.

This is an example of what a loop (specifically a FOR loop) is needed.

How do I know? Because there is some series repetition going on here.

Whenever you see repetition in code like this, it's probably a good idea to consider using a loop.

So how could we use a for loop to create the same output as the program above? Let's find out:

for (var i=1; i<=15; i++)
{
  console.log(i);
}

Done and done!

What Are the Inner Workings of the FOR Loop?

Here's what's going on in the FOR loop:

First it will run the initialization statement (it only runs this code once), that's the code that declares the variable i and sets it equal to 1.

Now that the for loop has declared the variable that it will be using to "execute" the loop, it moves on to check and see if it should terminate the looping... I know, it's a bit silly that it should have to check IMMEDIATELY if it should stop looping before its had a chance to do even ONE iteration, but believe it or not, this is a good thing, as it's predictable.

So, since it checks to see if it should terminate, it will run the termination condition, which at this point would be "Is i less than or equal to 15", and since i was just initialized as 1, it's checking if 1 is less than or equal to 15. Last time I checked, this was true, so it will execute the code inside the scope of the FOR loop.

The code inside the scope of the FOR loop is console.log(i), and remember that the current value of i is 1, so it will output "1" to the console. Great!

Then, since there's only one line of code in the scope of the FOR loop, it will try to loop over the entire scope of the FOR loop again. But before it loops, it need to go through a process that it ALWAYS goes through, which is to run the code in the iteration statement, then run the code in the termination condition statement.

Keep in mind that it ALWAYS runs the code in the iteration statement, then it runs the code in the termination condition statement. Over and over and over and over until the termination condition evaluates to false.

So for our example, what happens?

Well it runs the iteration statement, which is just i++, which increments the value of i by 1. So i now equals 2!

Then it runs the termination condition statement... "Is 2 less than or equal to 15?", yes it is! So... iterate again!

It will then output the number 2 to the console. Then it hits the end of the scope, so it will need to iterate, and possibly terminate. And round and round it goes until eventually, i is incremented to 16. Then when it runs the termination condition and asks "Is 16 less than or equal to 15?" the answer is false, so it terminates the loop.

And the result is that it has now outputted the numbers 1 through 15 to the console... which is exactly the same result as our code where we didn't use the for loop... but with our for loop program, we wrote a LOT less code!

Imagine if our requirement was to output the numbers 1 through to 1 million onto the screen... that would be a TON of typing if we weren't using a for loop. But WITH a for loop, it's the same amount of code as when we wanted to show numbers 1 through 15.

Neat right?

Thank god for FOR loops :)

In Summary

Programming languages need loops. Without them, we just wouldn't be able to create the programs that we have available today.

Loops are not only a time saver, but have also saved the fingers and wrists of hundreds of thousands of programmers, possibly thwarting a global epidemic of carpal tunnel syndrome. So be sure to send a thank you letter to the creator of loops! And hey, if you happen to know who it was that created loops in programming, let me know in the comments section below.

And as always, don't forget to enter your email address in the box below this post. I'm giving away a free goodie for everyone who signs up, and it's sure to turn you into an even smarter cookie than you already are... and hey, no need to send me any thank you letters, it's my pleasure!

{ 0 comments }

IF Statements in JavaScript

Chances are you already have some experience with programming as this blog namely focuses on the Java programming language.

If you have a background in Java, then the structure of the IF statement in JavaScript will look very familiar to you. In fact, it’s identical, so if you feel like reading more about it then by all means feel free, but it will just serve as review.

This article is written for those of you who haven’t a clue how to write an IF statement, and perhaps you’re even confused as to what an IF statement is. If that’s you, then you’re in the right place.

What is an IF Statement

An IF statement is a type of control structure.

Control structures represents the concept of modifying the flow of execution of the code in your program.

So, typically speaking, the code you write will be “executed” by the JavaScript engine from top to bottom and left to right.

This means that if you write 10 lines of code, it will execute each line of code, one by one from line 1 to line 10.

Here’s an example:

console.log("I'm the first line of code");
console.log("I'm the second line of code");
console.log("I'm the third line of code");
console.log("I'm the fourth line of code");
console.log("I'm the fifth line of code");

When you run the above code, it outputs the following:


I'm the first line of code
I'm the second line of code
I'm the third line of code
I'm the fourth line of code
I'm the fifth line of code

So, as you would have expected, you see the output of the five lines of code appearing one by one in proper order. This is because the code is executed from top to bottom.

Now, like I mentioned above, the concept of a control structure is to modify the flow of your code. So it could mess with the default “top to bottom” ordering. Of course, this modification of the flow of code isn’t random, it’s chosen specifically by YOU the programmer. You can use different kinds of control structures to modify the default flow of the code.

So in the case of the IF statement, you can have the JavaScript engine SKIP certain lines of code.

How an IF Statement Works in JavaScript

An IF statement is made up of three main parts.

  1. The if keyword
  2. The condition
  3. The scope

Knowing that you’ll need to use the “if” keyword is hopefully pretty straightforward, so I’ll just fly on by that part and talk about the condition.

An if statement requires you to have a condition, as this is the fundamental aspect of the if statement.

There needs to be some sort of a “question” being asked and answered (the condition). The condition MUST be a true or false (yes or no) question. If the condition is NOT a true or false type of question, then you’ll get an error and your program won’t run properly.

If you’ve structured your condition to be a true or false question, then you must outline the scope of your if statement.

By “scope”, I mean how much of your code will be affected by the if statement. You see, an if statement’s purpose is to SKIP a certain number of lines of code when the condition’s answer is false.

This means that if the question asked inside an if statement results in a false, then the JavaScript engine will skip ALL the code that is contained within the scope of the if statement.

At a minimum you must have one line of code that the if statement can affect, at the maximum, you could put your entire program inside of one if statement… however, this would be a bit silly and not practical.

Alright, so now that we’ve talked about the main aspects of the if statement, let’s talk about syntax.

Syntax of an IF Statement in JavaScript

Let’s assume that we want to modify our previous code and change it so that it will NOT output the first piece of text. In other words, we want it to omit the sentence “I'm the first line of code“. How do we do this?

Well, before we can write our code, we need to determine what our condition is going to be!

In this case, let’s keep things simple and base our condition around the value of a boolean variable called showFirstLine.

So the showFirstLine boolean variable will have either a true or false assigned to it. In our example below, we’ll set it to false (as we want to skip the first line of code):

var showFirstLine = false;
if (showFirstLine == true)
{
  console.log("I'm the first line of code");
}
console.log("I'm the second line of code");
console.log("I'm the third line of code");
console.log("I'm the fourth line of code");
console.log("I'm the fifth line of code");

Alright, so what we see above is that we’ve declared our showFirstLine variable and assigned it the value of false as promised.

Now because the showFirstLine variable is set to false, it will have a “skipping” effect on any conditional statement.

You’ll notice that we refer to the showFirstLine variable inside of our if statement above. We ask the question “is showFirstLine equal to true?” (this is the conditional part of our if statement). Since the answer to this question is false, the JavaScript engine will SKIP the entire scope of the if statement.

The “scope” is measured by the open and closing curly brackets {} in the code snippet above. Do you see how the code console.log("I'm the first line of code"); (on line 4) is “wrapped” inside of the scope of the if statement? This means that the “scope” of the if statement only applies to line 4 of our program above.

Therefore, since the conditional statement (the question) evaluates to false, the JavaScript engine will skip everything inside of the scope and therefore will NOT output the string to the console. The resulting output will be:


I'm the second line of code
I'm the third line of code
I'm the fourth line of code
I'm the fifth line of code

The IF..ELSE Statement in JavaScript

Alright, having seen the basic IF statement, let’s get a bit more advanced and talk about the IF..ELSE statement.

This concept is very common inside of all programming languages.

The IF..ELSE statement was created for those times when you have more than two possible outcomes for a specific question.

So, in the case of our example above, we just had two possibilities for outcomes, true or false. This was the case because we were using a boolean as our variable inside of the if condition.

Now let’s use a variable that has more than one outcome. Let’s use a number!

How about we try to write some code that will only output a single sentence from our example program? Let’s write it so that we have to enter a number (from 1 to 5) that represents which sentence we wish to see.

So if the variable is set to 1, it will output “I’m the first line of code”, if the variable is set to 3 then it will output “I’m the third line of code”.

Make sense?

Let’s have a look at the code:

var lineToShow = 1;

if (lineToShow == 1)
{
  console.log("I'm the first line of code");
}
else if (lineToShow == 2)
{
  console.log("I'm the second line of code");
}
else if (lineToShow == 3)
{
  console.log("I'm the third line of code");
}
else if (lineToShow == 4)
{
  console.log("I'm the fourth line of code");
}
else
{
  console.log("I'm the fifth line of code");
}
console.log("We're done!");

So in the code above, we have a couple of things going on. The first thing to note is that we now have a bunch of if statements, and all of our if statements are asking a question related to the lineToShow variable. And, we also have that last part which doesn’t ask a question, it just says else.

Allow me to tackle the first part of what’s going on here, and it relates directly to code flow.

With an IF..ELSE statement (which really in this case is the IF..ELSE IF..ELSE statement, but that’s just too long to write) the flow of your code will only go into ONE of the scopes of the overall if statement. This is directly related to the fact that we are using the keyword else if (and else) in our overall if statement structure.

This means that once ANY of the conditional statements evaluate to true, it will execute the code within the scope of that if statement, and then then JavaScript engine will skip ALL the rest of the code that pertains to the overall if statement.

In the next section, I’ll be sure to show you a visualization of the code flow so that it’ll make more sense to you.

But before I jump to the visual part of the description of an IF..ELSE statement, I want to talk about the ELSE part of the if statement.

In the event that NONE of the conditions in the overall if statement structure evaluate to true, then the code will automatically flow into the else scope of the if statement.

Having said that, the output for the code above would be:


I'm the first line of code
We're done!

A Visual Look at the IF..ELSE Statement

Because I’m such a visual person, I want to give you an idea of what lines of code will be executed by the JavaScript engine. I’m going to use some yellow highlighting to indicate that the JavaScript engine has traversed over a line of code.

I’ll start with the most recent code snippet:

var lineToShow = 1;

if (lineToShow == 1)
{
console.log(“I’m the first line of code”);
}

else if (lineToShow == 2)
{
console.log(“I’m the second line of code”);
}
else if (lineToShow == 3)
{
console.log(“I’m the third line of code”);
}
else if (lineToShow == 4)
{
console.log(“I’m the fourth line of code”);
}
else
{
console.log(“I’m the fifth line of code”);
}

console.log(“We’re done!”);

So you see that once the JavaScript engine goes into the scope of the first part of the if statement, it exits the overall if structure and doesn’t even try to evaluate any of the ELSE IFs or the ELSE. This is just how the if statement control structure works in terms of the flow of code.

Let’s use another piece of code where we’ll change the lineToShow variable to a different value. Pay attention to the difference in the way the code flows in the following example:

var lineToShow = 3;

if (lineToShow == 1)

{
console.log(“I’m the first line of code”);
}

else if (lineToShow == 2)

{
console.log(“I’m the second line of code”);
}

else if (lineToShow == 3)
{
console.log(“I’m the third line of code”);
}

else if (lineToShow == 4)
{
console.log(“I’m the fourth line of code”);
}
else
{
console.log(“I’m the fifth line of code”);
}

console.log(“We’re done!”);

So you see here how it evaluates but skips the scope of the if statements that correspond to lineToShow == 1 and lineToShow == 2? This is because it the if statements there are evaluating to false, and therefore the JavaScript engine doesn’t go in and execute the code inside of their respective scopes.

Okay, let’s look at one last example. I’m going to change the value of lineToShow to be something other than 1 through 4:

var lineToShow = 53;

if (lineToShow == 1)

{
console.log(“I’m the first line of code”);
}

else if (lineToShow == 2)

{
console.log(“I’m the second line of code”);
}

else if (lineToShow == 3)

{
console.log(“I’m the third line of code”);
}

else if (lineToShow == 4)

{
console.log(“I’m the fourth line of code”);
}

else
{
console.log(“I’m the fifth line of code”);
}
console.log(“We’re done!”);

Voila! You see that the JavaScript engine has to go through and evaluate EACH of the IF..ELSE IF statements and finally (since they’re all false) it goes into the ELSE scope and executes that code, then exits.

Hopefully the visual breakdown here has helped you better understand how the IF..ELSE statement structure works.

In Summary

IF statements are extremely common in the programming landscape, and the JavaScript language is no exception to that rule.

If you’re having trouble understanding how this stuff works, please feel free to leave a comment below and ask me a question, I’ll answer it ASAP.

And I’d also suggest you enter your email address below, you’ll get a cool “goodie” delivered directly (and instantly) to your inbox.

{ 0 comments }

JavaScript Data Types

Although the JavaScript language doesn’t allow you to explicitly define a type when you declare a variable, this shouldn’t lead you to believe that JavaScript doesn’t have types (because it does).

JavaScript uses dynamic typing, and therefore this means that the JavaScript engine will choose the best data type for your variable based on its value.

So this begs the question, what data types could the JavaScript engine choose for my variable?

Here’s a quick summary of the JavaScript Data Types:

Data Type Example
Boolean  
var x = true;
var y = false;

 
Null  
var person = null;

 
Undefined  
var person = undefined;
var variableWithNothingAssigned;

 
Number  
var x = 1.2;
var y = 32;

 
String  
var aString = "What up dude!";

 
Symbol  
const MY_KEY = Symbol();
let obj = {};

obj[MY_KEY] = 123;
console.log(obj[MY_KEY]); // 123

Object  
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

 

Boolean Data Type

The Boolean data type in JavaScript is a primitive type.

It is a pretty straight forward data type as it only contains two valid values (true, false).

Booleans are used when testing conditions. Conditions are found inside of control structures like an if statement (which we’ll talk about in the next article), or a while loop.

You’re probably already familiar with the concept of Booleans, so let’s move onto the next data type.

Null

It’s perhaps a bit strange to have null exist as a data type, but nevertheless it does in JavaScript.

Another strange bug inside of JavaScript is that if you inspect the “typeof” null, you’ll actually receive Object as the type.

In any case, in an attempt to stop confusing you, just know that null is used to represent “nothing”. It’s typically used as a place holder for an object.

Undefined

Not to be confused with null, the undefined data type in JavaScript is used to tell the coder that a variable has been declared but hasn’t yet been assigned any value.

So when we write the code var aVariable;, the resulting data type for aVariable would be undefined as we haven’t yet assigned a value.

What you could do if you wanted aVariable to no longer be assigned as an undefined data type, but still didn’t want to assign anything truly meaningful, you could assign it the null type.

Number

What I personally enjoy about JavaScript is that it only has one data type to specify a number, and that’s just the Number data type.

When you think about the Number data type in JavaScript as it relates to the Java language, you can state that a Number in JavaScript can be an Integer, a Double, a Float, or a BigDecimal all at the same time. So you don’t need to worry about the crazy details about how JavaScript is going to handle your numbers!

One helpful function in JavaScript that relates to the Number data type is the isNaN() function.

This function is used to determine if a value is “Not-a-Number”. It’s a bit confusing as you’re working on things in the “negative”, so if you want to check if something is a number you’re looking for a boolean value of false when running the isNaN() function.

String

A String is likely the most commonly used data type across any modern programming language.

A String is a data type that represents any combination of characters, special character and/or numbers that are assigned to a variable. Typically, Strings are used to store English language sentences, names, or even numbers!

You can think of Strings as a sort of “catch-all” for all the data types. What I mean by this is that if the JavaScript engine can’t figure out what data type to assign your variable, it’s probably going to just assign the String data type to your variable.

Strings also have a wide variety of functions and properties that make them extremely versatile and useful in the JavaScript language.

We’ll be diving into details in later articles with respect to all the things that you can do with Strings.

Symbol

The Symbol data type is a new addition to the JavaScript language.

It’s unique and immutable. It’s unique because any Symbol that is created in your code is guaranteed to be different from any other Symbol you create. It’s immutable because you will not be able to change the value of any Symbol after it has been created.

Symbols are typically used as keys for properties due to the fact that they are unique and immutable.

If you want to read more about Symbols, I found a great article here.

Object

Probably the most powerful and flexible data type in JavaScript, the Object data type is the only type in JavaScript that isn’t a primitive type.

Since the JavaScript language is Object oriented, the Object data type exists to fulfill its obligation.

What’s neat is that you can create an Object and assign properties to it in two different ways.

The first is to create properties in an Object by using dot notation like so:

var person = {}; // note that we use the open/close curly braces to declare a variable as an Object type
person.name = "Trevor Page";
person.age = 32;
person.gender = "Male";

This will create an Object variable called person with three properties that you’ll be able to access like so:

console.log(person.name); // outputs "Trevor Page"
console.log(person.age); // outputs 32;
console.log(person.gender); // outputs "Male";

Alternatively you can also use something called JSON (which is an acronym for JavaScript Object Notation) to create an Object in JavaScript.

The equivalent person Object can be created with JSON like so:

var person = {name: "Trevor Page", age: 32, gender: "Male"};

Note: There are subtle differences between the two person objects that get created by the JavaScript engine, but these differences aren’t worth mentioning now as they are a more advanced topic.

{ 2 comments }

JavaScript Variables

Programming 101 - the 5 fundamental elements of any programming language
Variables in JavaScript are pretty straight forward once you understand the concept of dynamic typing, which we talked about in the last article.

Variables in JavaScript are used like variables in any other programming language. They are used to store data for the period of time that a user has a particular web page loaded.

Let’s say we want to keep track of someone’s name while they are visiting a particular webpage, we could collect their first name using something like the prompt keyword in JavaScript (which we’ll talk about in a later article). Once we’ve prompted the user for their name and they have entered it, we would need to store it somewhere… this is where variables come in handy.

To store something like a name, we’d use code like this:

var myName = "Trevor Page";

When you’re declaring a variable in JavaScript, there are two mandatory things (and one optional thing) you need to use:

  1. The var keyword (mandatory)
  2. The name of the variable (mandatory)
  3. A value for the declared variable (optional)

In the example above, we’ve used the keyword var which tells the JavaScript engine that we wish to declare a variable. We also specified a name for the variable, in this case we used myName as the variable’s name. If you’ve ever used a programming language before, you should be completely comfortable with this. If this is your first time, then keep reading. Finally, and optionally, we’ve assigned a value to our variable: "Trevor Page" is the String we’ve assigned.

Now if we were to type in the variable name myName somewhere below the example code above, then we can retrieve the value that’s been stored in our variable.

JavaScript Variables in Action

To display what we have stored in our variable, we could use the alert function to display a popup alert on the screen showing the contents of the myName variable.

Here’s what that code would look like:

alert(myName);

All this code will do is display an alert box which will contain the contents of the myName variable.

Let’s actually SEE this code in action shall we? Go ahead and click the button below and then type in your name:


Note: Feel free to click on this button multiple times and enter different names every time, you’ll see that the values you enter each time are stored into the myName and will override the previous value.

A Quick Note on JavaScript Variables

Remember that with JavaScript, variables are dynamically typed, so this means that you do NOT need to specify if your variable should be a String, or an Integer, or whatever other data types exist in JavaScript. The JavaScript engine will run an algorithm in the background and determine what the type of your variable should be on your behalf.

This is a time saving process that will free up your precious brainpower to focus on more important things, like what to eat for dinner!

In Summary

Since JavaScript handles a lot of the grunt work when it comes to variables, there’s really not much else to talk about.

If this is your first time learning about variables, I’d also suggest you read another article where I go in depth on how variables work (as they pertain to the Java language), just click here to read more about variables.

And as always, don’t forget to fill out the form below and receive a free goodie delivered directly to your inbox. More detail on the free swag below!

{ 0 comments }

Dynamic Typing vs Static Typing

Generally speaking, modern day programming languages fall into one of two categories:

  1. Dynamic Typing
  2. Static Typing

Dynamic Typing vs Static TypingBefore we can dive into what dynamic or static typing means, we’ll first need to understand what it means by “typing” in general.

Note: This concept actually reaches beyond just JavaScript and Java, but for the scope of this conversation we will be using JavaScript as the example for dynamic typing and Java as the example for static typing.

What is Typing in Programming?

The first place I want to start is to talk a little bit about the concept of typing.

When we say “typing” we’re referring to the concept of applying a “type” to a variable.

I’m going to assume you’re familiar with Java already, but if you’re not, what better place to learn about Java than right here!

So, in Java, we always assign a type to our variables. For example:

String greeting = "Hello!";
Integer someRandomInteger = 100;
Double aDoubleVariable = 2.2;

In all three of these variable declarations above, we have assigned a variable type to each variable. The reason we have done this is because Java is statically typed and therefore we are forced to assign an exact type to the variables before we can use them.

Having a type is important in programming because it allows the language to decide what to do with your code in certain situations.

For example, if you have two Integers and you tell it to add the two together, because they are Integers, the language knows to use addition… however, if you had two Strings and added them together, because they are Strings, the language knows to concatenate them (not add them).

Make sense?

Types are important.

Having said that…

Dynamic vs Static Typing

The difference between dynamic and static typing is that with dynamic typing, the programmer is not required to specify any types for the variables they create.

How neat is that?

This means that with languages that use dynamic typing, you don’t actually have to decide if the variable you’re creating should be a Double or a Float or a String or an Integer etc.

All you need to do is just tell the language that you want to create a variable and you go about your business assigning whatever values you like to it.

So let’s recreate the declaration of those three Java variables using the JavaScript syntax:

var greeting = "Hello!";
var someRandomInteger = 100;
var aDoubleVariable = 2.2;

When we execute this code in JavaScript, the JavaScript interpreter (a.k.a the JavaScript engine) will look at the values that are being assigned to the variables you’ve declared and decide for itself what “type” to assign the variables in the back-end.

Having said that, it’s very important to understand that just because you didn’t have to assign any types to your variables, doesn’t mean that JavaScript doesn’t have types… because JavaScript definitely does have types.

You’ll be introduced to the typeof operator in a couple of weeks. It’s used to determine what type is assigned to your variables.

How Dynamic Typing Works in JavaScript

The concept behind how dynamic typing works in JavaScript is actually pretty straightforward.

The JavaScript engine will choose a type that it feels best describes the data that’s contained inside of your variable. So when you create a variable and assign it the value of "Hello there!", the engine will realize that this is a String and it will assign that as the datatype behind the scenes.

This means that if the JavaScript engine has chosen the String datatype in the back-end, and you were to add another string to this variable, it would know to perform string concatenation and not addition.

So all the same rules of variables that you’re already familiar with, still apply. There’s just a algorithm that works on your behalf to assign a type to your variables.

We’ll go into more details about what implications dynamic typing has to your coding in the next article when we dive further into JavaScript variables.

To Summarize

If you come from a Java background, it might be a little bit of an odd transition into a dynamically typed language like JavaScript, but the most important thing you need to remember is that there are still types that back all of your variables.

You just need to sit back and enjoy your new-found freedom of not having to think about what types to assign to your variables when you declare them! Just declare those variables and walk away :)

And as always, be sure to join our email list below and receive a free gift directly to your inbox. You can read more about what I’m giving away as a free gift below this post!

{ 1 comment }

What is JavaScript?

What is JavaScript?JavaScript is an object oriented programming language that was created specifically for the web. JavaScript adds functionality and interactivity to websites by allowing your plain old HTML pages to actually have their own programming language embedded inside of them.

You see, HTML isn’t really a programming language, it’s what’s known as a “markup” language, which is really just used to describe how to present text in your browsers.

So what JavaScript brings to the table are all of the common programming elements to your HTML pages.

This means you’ll be able to use fun things like control structures, data structures, data validation, even an in-browser database if you feel the need to get fancy!

JavaScript brings websites to life and makes them more than just a glorified electronic newspaper.

Java is NOT JavaScript

Although they share the same root word, these two programming languages are quite different in the way they work under the hood.

Sure a gas powered car and an electric car are both cars… but they use very different means of propulsion. Same concept applied with Java and JavaScript. They’re both programming languages, but they live in very different worlds.

Where Can I Download JavaScript?

A common thought that Java programmers have when learning JavaScript is “Where do I download the JavaScript programming language so I can start using it?”

Well the beauty is that you don’t need to download it, JavaScript already exists inside of any internet browser you use. Just goes to show you how tightly coupled HTML and JavaScript are 😉

So that brings me to my first real talking point about JavaScript.

Because JavaScript exists inside of the browser, this means that it’s a client-side programming language.

JavaScript is Client-Side, Java is Server-Side

We call JavaScript “client-side” because all the code that you write will actually exist inside your users’ browsers and that code will be executed by the JavaScript language that ALSO exists on your users’ browsers.

Compare and contrast this “client-side” idea to the Java language. Java is a “server-side” language. This is the case because when one of your users interacts with a web application that’s powered by Java, the user won’t ever see your Java code. The Java code exists on YOUR web server (either in your house or in some hosting companies data-center), never on the users’ computers.

This client-side vs server-side distinction is just the start of many important differences between the two programming languages.

So, When Should I use JavaScript?

Alright, so one language exists in the browser, and on exists on a server… so… in what situation should I use JavaScript and in what situation should I use Java?

This is a great question!

The answer will depend on the project you’re working on. You see, Java is typically chosen as the “go-to” programming language when you want to build “enterprise” level applications. What this means is that if you’re wanting to build an application that will be used for business purposes and will be a fairly large application with hundreds or thousands (or millions) of users, then Java is probably your language of choice.

If you’re building a smaller application, like a single player game that won’t require concurrent users, or if you’re building a simple application to handle the processing of forms, then JavaScript might be your go to language. Or perhaps you wish to build an “offline” web application, one that can be used with or without an internet connection, then JavaScript with HTML5 is a great option!

The big thing to point out here is that this isn’t a “one or the other” type of scenario. When I build my web applications, I use BOTH Java and JavaScript.

I typically use JavaScript to be my “front-line” or “presentation layer” support for validating any forms, interacting with the users and dynamically changing the elements on an HTML page. Then I’ll use the Java language on the back end in the “business layer” of the application to process the data that was validated and sent from the “presentation layer” (or HTML + JavaScript layer).

So Java and JavaScript actually play quite well with each other.

How else are Java and JavaScript Different

Well one big difference you’ll notice between the two languages is how JavaScript’s variables work.

You see, JavaScript uses something called Dynamic Typing. This is a topic that we’ll cover in the next article. But the quick version is that you don’t need to assign a “type” to your variables like you do with Java. Java uses something called Static Typing, which requires you to declare what types your variables will be (i.e. String, Integer, Double, etc).

JavaScript uses a sort of “guessing system” to choose a data type on your behalf so you don’t need to. But like I said, we’ll talk more about that in the next post.

In Summary

JavaScript is here to stay and it’s an extremely useful language to learn and use. I’m actually predicting that JavaScript will knock Java off of it’s #1 spot as the most popular programming language in the coming years.

JavaScript is embedded right into your browser and it was designed to easily interact with HTML elements, so it’s the perfect language to use when you want to “spice up” your boring HTML web pages with dynamic programming.

{ 0 comments }

HTML Images

html imagesWelcome to yet another tutorial on HTML tags.

Today’s lesson will revolve around the img tag, which is short for “image” of course.

Whenever you see an image on a webpage, it’s most likely because the creator of the website is using an img tag.

Thankfully, there’s really not much to learn about images, so let’s dive right into it!

How to insert an image on a web page

When it comes to inserting images into your web pages, you really only need to remember two things:

  1. You need to use the img tag
  2. You need to specify the URL (the src) that points to the image’s physical location

Once you have these two things, you’re ready to insert an image onto a webpage.

In this example we are going to assume that you’ve already uploaded an image to some sort of web server. If you haven’t done this already, then pointing the src to your hard-drive will work, but keep in mind that if you publish the web page on the internet, the images won’t load… we’ll talk more about that later.

Okay, so here’s some code that will load an image that’s stored on this website:

<img src="https://howtoprogramwithjava.com/wp-content/uploads/2012/09/Java-Podcast.jpg" />

The above code will result in the image being displayed on your web site like so:

Now, the obvious thing to note here is that the image being loaded is VERY LARGE! And thus, it’s not exactly ideal for display purposes… it’s a bit ugly and distracting.

So how do we address this issue?

Resizing an Image with CSS

So what we’ll need to do here is introduce a bit of CSS magic to reduce the size of the image. This can be done by utilizing the style property and using the width attribute (or the height attribute).

As you shrink the width of the image, the height of the image will automatically shrink as well to keep the width to height ratio of the image intact… this is a good thing, otherwise your image will look like it’s being squeezed and will look horrible.

So let’s take a look at some code that will assign a new width to the image… for the purposes of this tutorial I’m going to use “size units” known as px (short for pixels), but I think it would be beneficial for you to also learn about the em unit in html. When you have a moment, read about them here.

<img src="https://howtoprogramwithjava.com/wp-content/uploads/2012/09/Java-Podcast.jpg" style="width: 200px;"/>

Here’s what the resulting image would look like:

So, can you see how much easier it is to “digest” this image now?

Much smaller and nicer.

Image Loading Times on the Web

Having shown you how to reduce the size of your images for the sake of pleasing one’s eyes, now I want to tell you about how you can please your users bandwidth.

You see, even though the 2nd image is smaller to the eye, it’s not smaller to the browser. Both of those images are 161 KB in size.

This concept is quite important to understand, as a lot of people assume that if the image LOOKS small, that must mean that it IS small in terms of Kilobytes, what that’s just not true at all.

So what are the implications?

Well, what happens if you’re forcing all of your users to download MASSIVE images (say 10 Megabytes each), yet they all appear as small pictures on screen… I’ll tell you what will happen, the page will take FOREVER to load (especially on a mobile device).

The implication here is that a lot of people are impatient when it comes to loading websites, and a lot of people will just hit the “back” button and leave your website (most likely never to return). Uh oh! That’s not what we want right?

So how do you fix this issue? Easy, just use a tool that will shrink the sizes of your images before you upload them to your web server. Just do a Google search for something like “Image Size Shrinker” and you’ll find plenty of online tools that will do this for free.

A popular method of image shrinking is to upload both the original (BIG) picture and the “optimized” picture, but only have your webpage load the optimized picture while allowing your users to click on the image to see the full-size (BIG) version of the file.

Turning Images into Links

This seems like a great time to talk about making images that are also links.

In the scenario I described above, I talked about a small image that, when clicked, loads the big image version in a new URL. Let’s take a look at how we’d accomplish that:

<a href="https://howtoprogramwithjava.com/wp-content/uploads/2012/09/Java-Podcast.jpg"><img src="https://howtoprogramwithjava.com/wp-content/uploads/2015/07/Optimized-Java-Podcast.jpg" style="width: 200px;"/></a>

So in the code above, we’ve created an anchor tag that links to the BIG version of the image, and and wrapped inside of that is the img tag that will show/load the smaller version of the image. So the result is that when this webpage loads, it will only be “forced” to load the small version of the image, and the user can then choose the view the bigger version just by clicking on the smaller image.

Here’s what that would actually look like:

Note: this image is clickable, go ahead and click on it to see what loads!

In Summary

As always, there’s more to images than just these basic things that we’ve just learned… but the stuff I didn’t cover isn’t used too often. But for the sake of completion, I’d recommend checking out the HTML Img tag article via W3Schools here.

And don’t forget to join our email list, I send you a “goodie” to your email inbox just for joining and you’ll continue to receive awesome exclusive content that’s only available to my email subscribers. So go ahead and fill in your best email address in the box box below to get started now!

{ 0 comments }