≡ Menu

The Document Object Model (DOM)

The DOM is something that intimidated me for quite a while (even as a senior software engineer), but this was only because I didn’t understand what it was, and never took the time to learn.

I assure you, if you’re feeling intimidated by the DOM, you don’t need to be!

DOM stands for Document Object Model and it exists so that you can interact with HTML elements using JavaScript. That’s really all there is to it from a 30-thousand foot view.

How the DOM Works

When a webpage is loaded, a Document Object Model is created.

The important thing to remember here is that we’re talking about Objects, specifically, JavaScript objects.

So a “model” is created, whereby all the elements of the HTML page are loaded up as objects so that you can interact with them.

Here’s a great visual representation of the DOM:

The Document Object Model

(Photo credit goes to W3Schools)

Accessing HTML Elements

So every element in the HTML page get assigned to its own Object, and along with that Object you’ll also be able to access the HTML element’s properties too.

And believe it or not, you’ve already seen all of this in action before. We recently talked about all the built in objects that JavaScript has, and in that lesson we saw how we can load up HTML elements as objects using the getElementById() method in JavaScript.

The whole reason why you’re able to “call up” HTML elements in JavaScript is because of the DOM.

No DOM, no interacting with HTML, sad days.

Changing HTML Elements

And the DOM is not only used to retrieve HTML elements, but also to change them as well.

You’ll recall that we changed some of the style properties associated with a paragraph when we talked about the built in document object.

Not only can you change HTML elements via the DOM, but you can also add and delete elements as well.

It slices, it dices, but wait, there’s more!

There are plenty of things that you can do with the DOM, but they’ve all been outlined and explained to death out there on the interwebs and the concepts aren’t hard to grasp. So instead of having me just rehash existing content, I think I’ll turn this one over to the good people at W3Schools.

Have a gander at their tutorial on the DOM here.

{ 0 comments }

JavaScript Assignment #2 – Creating a Set

JavaScript Assignment 2 Creating SetsIn today’s assignment we are going to tackle an issue that exists within JavaScript.

That issue is the fact that JavaScript has no Set data type. Gasp!

In Java, we use Sets like a type of array, only it doesn’t allow duplicates to be added.

So if you were using a Set and tried to insert the following elements:

1, 2, 3, 3, 4, 5

The resulting Set would only contain 5 elements even though you tried to add 6 elements.

The reason for this is that it would detect that you tried to add the number 3 twice. So the first time you insert 3, it accepts it and inserts it into the Set, but the second time you try to insert the number 3, it will NOT insert that element.

Everything else about a Set more or less acts like an array, so that’s the only thing we’ll concern ourselves with for this assignment.

What I want you to create is a method that will mimic the behavior of a Set in Java when you try to insert an element.

Here’s a basic outline of how it should work:

/** This function will only add numeric elements onto the end of the array
**   if the element being passed in doesn't already exist within the array
**   If the element is added successfully, then the function returns true, else it returns false
**/
function addNumericElementNoDuplicates (element, array) 
{
 // Step 1: Validate the element being passed in is of type number
 // Step 2: If it's NOT a number, return false, else continue
 // Step 3: traverse the array to see if the element to add already exists
 // Step 4: If the element already exists, return false
 // Step 5: If the element doesn't exist, then add it to the end of the array and return true.
}

Once you have completed your method, try creating the following test cases to ensure your code is functioning correctly.

Test Case 1

var myArray = [];
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(2, myArray);
addNumericElementNoDuplicates(3, myArray);
addNumericElementNoDuplicates(3, myArray);
addNumericElementNoDuplicates(4, myArray);
addNumericElementNoDuplicates(5, myArray);
console.log(myArray);

This test case should output the following to your console:

[1, 2, 3, 4, 5]

If it outputs anything else, then you likely have a bug in your code.

Test Case 2

var myArray = [];
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(2, myArray);
addNumericElementNoDuplicates(3, myArray);
addNumericElementNoDuplicates("test", myArray);
addNumericElementNoDuplicates(4, myArray);
addNumericElementNoDuplicates(5, myArray);
console.log(myArray);

This test case should output the following to your console:

[1, 2, 3, 4, 5]

If it outputs anything else, then you likely have a bug in your code.

Test Case 3

var myArray = [];
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(1, myArray);
addNumericElementNoDuplicates(1, myArray);
console.log(myArray);

This test case should output the following to your console:

[1]

If it outputs anything else, then you likely have a bug in your code.

In Summary

If you managed to implement the addNumericElementNoDuplicates method such that you get the expected results in all three test cases, then you have done a great job.
You can consider this assignment complete!

But, don’t throw away you code, because we’re going to use it as part of our next assignment. So keep that code in a safe place.

And if you really enjoyed this assignment (and haven’t done so already), be sure to join our mailing list! I send out cool and helpful JavaScript material on a regular basis, you’ll surely upgrade your JavaScript skills after a few weeks of my lessons!

{ 0 comments }

Arrays in JavaScript

So we’ve talked a lot already about all the different data types and built-in objects in JavaScript, but not once have I mentioned Arrays.
Arrays In Javascript
The reason for this is that the topic of Arrays is quite a broad one and it will require you to understand many of the base mechanics of the JavaScript language before you can jump in.

Having said that, I believe your moment has arrived, you are now ready.

How to Create an Array in JavaScript

Believe it or not, JavaScript actually has two ways of creating an Array.

  1. Using square brackets (aka. array literal)
  2. Using the new keyword

Creating an Array Using Literals

Here’s an example of how to create an Array using the first method:

var myArray = ["first element", "second element", "third element"];

You see here that we’ve used square brackets to create an array that has three elements. In this case we’re storing strings inside of the array, but we really could have used any data type we wanted. You can even mix and match data types in your arrays like so:

var myArray = ["first element", 2, 10.2, {firstName: "Trevor", lastName: "Page"}];

Here we have inserted a string, two numbers and an Object.

This kind of mix and match isn’t recommended though, as it’s pretty confusing and would be strange to iterate through. But, it’s interesting to note that you can do it, right?

Creating an Array Using the new Keyword

Alright, now let’s take a look at the second way to create an Array.

It’s worth noting that this method for creating an Array isn’t recommended as it’s not as efficient and has some quirks. So it’s always suggested that you create an array using the array literal syntax above.

In any case, you will most likely run into the code that uses the new keyword to instantiate an Array in JavaScript. So let’s take a look at an example:

var myArray = new Array(3);
myArray[0] = "first element";
myArray[1] = "second element";
myArray[2] = "third element";

When you place a number inside of the round brackets of the Array instantiation, this tells JavaScript to allocate three spots for the array. However, with JavaScript, arrays are implemented as objects and can therefore be extended beyond what was initially set as.

Just as in most (if not all) programming languages, JavaScript uses a zero based index for its numbering system with elements in an array. This means that the "first element" will be at index 0.

Accessing Elements in a JavaScript Array

As you’ve seen above, we are able to place elements into our arrays, but we haven’t talked about how to retrieve those items.

All you need to do is reference the index of the item you’d like to retrieve with the following syntax:

var firstElement = myArray[0];
var secondElement = myArray[1];
var thirdElement = myArray[2];

Pretty simple stuff. The hardest part is remembering the syntax.

One thing that’s interesting to note is that a JavaScript array doesn’t give you any errors if you try to access an index that doesn’t exist. In the Java language, if you’ve allotted 3 elements to exist inside the array, then try to access a fourth element, you’d get an IndexOutOfBoundsException… but in JavaScript, all you’ll get back is undefined, as you’re accessing an element that hasn’t yet been created.

Adding Elements to a JavaScript Array

So you’ve already seen how to place elements in a JavaScript array when it’s being created… but what about after it has been created? How do we insert elements then?

There are two ways:

  1. Using the push() method
  2. Assigning a variable to an index in the array directly

First let’s look at the push() method:

myArray.push("fourth element");
myArray.push("fifth element");
myArray.push(12);
myArray.push({objectProperty: "someProperty"});

This is also pretty simple stuff, each time you invoke the push() method, JavaScript will add the element you specified inside the round brackets to the end of the array.

OR…

You could just manually specify an index where you’d like to insert an element like so:

myArray[9] = "tenth element";
myArray[99] = "one hundredth element";

In the code above, we just specified the exact index where we’d like to insert an element.

The cool thing about JavaScript arrays is that they don’t really function like an array really, they operate like a Map. So you’re allowed to have “holes” in the array. As you can see, we assign an element to index 9, and then we assign an element to index 99… again, in Java, this is sinful, but in JavaScript it’s perfectly legal.

Again, it’s not very useful if you’d like to have consecutive elements being stored, but you are free to utilize an array with gaps if that suits your needs.

Deleting Elements from a JavaScript Array

We know how to add, now let’s talk deleting!

One thing I wish the JavaScript Array had was something like a remove or delete method, but alas we must deal with something a bit more complex.

The method used to delete an element or elements from an Array is the splice method.

The splice method can actually be used to delete multiple elements (not just one), and it can even be used to insert elements into an Array at any index. So the splice method is quite flexible, but that’s exactly where I think it falls short. It just does too much and therefore I’m always looking up how to delete elements from a JavaScript Array as I keep forgetting how to use it.

Anyway, enough complaining, let’s look at an example. Let’s say we wanted to implement some code to delete the last element in a JavaScript Array. This is a common task, so it’ll be some useful code, here we go:

var myArray = ["first element", "second element", "third element"];
myArray.splice(myArray.length-1, 1);

So, what’s going on here is that the splice method takes two parameters by default. Both are required.

The first specifies the index at which you’d like to delete elements, the second parameter says how many elements you’d like to delete.

So in this case, we’re passing in myArray.length-1 as the index from which we’d like to start deleting. Since the Array‘s length is 3, this means that we’ll start deleting at index 2. Then we specify that we’d like to delete one element, so it will just remove the last element in the Array.

Alright, but I also mentioned that the splice method can insert elements as well! So let’s now try and insert an element in the middle of our Array while deleting an element as well… you see how complicated this can get? Jeez!

var myArray = ["first element", "second element", "third element"];
myArray.splice(1, 1, "random middle element");

So, the code above will do two things, first it will delete one element at index 1. Since Arrays use a zero based indexing system, this means that we’re deleting the second element… THEN, we are telling it to add the "random middle element", which will add the element at the index that you specified in the first parameter.

So the resulting array will look like this:

["first element", "random middle element", "third element"]

So you see here that the second element has been deleted and it has been replaced with a "random middle element".

It’s also pertinent to note that you can add as many elements as you like with the splice method. Here’s what I mean:

var myArray = ["first element", "second element", "third element"];
myArray.splice(1, 1, "random middle element", "another middle element", "yet another element", "etc");

The resulting array would then be:

["first element", "random middle element", "another middle element", "yet another element", "etc", "third element"]

Cooooooool.

Alright, then about sums up all the typical things that you can do with the JavaScript Array! For even more fun tricks, check out this article from W3Schools.

And since you’ve read ALL the way to the bottom of this post, you REALLY need to put your email address in the box below. We’ve got some great free JavaScript swag to send to you, check out the info in the box below for more details.

{ 0 comments }

JavaScript’s Built in Objects

javascript built in objectsSomething that’s really useful to know about is the handful of objects that come built into the JavaScript language.

These objects are tools that you can use to enable a wide range of useful functionalities in your applications.

From manipulating the user’s URL location to changing elements on the screen, these objects will make you say “Hey! That’s awesome!”

Here’s a brief outline…

The Full List of Built In JavaScript Objects

Built-in Object Used For
Document Used to access elements within an HTML page. This allows you to dynamically modify any element on the screen using JavaScript.

Location Used to access information about the current URL. The location object is part of the window object and is accessed through the window.location property. Commonly used to send your visitors to another URL based on some action taken by the user.

History Used to enable navigation through a user’s browser history. You can send them back to a previously visited page, or forward to a page they were just vieweing. The history object is part of the window object and is accessed through the window.history property.

Screen Used to get information about the user’s screen. Commonly used to get the width and height of the webpage their currently viewing.

Navigator Used to get information relating to the user’s browser. Commonly used to see what type of browser a user is using (i.e. Chrome, Firefire, Internet Explorer, Safari, etc.)

So there you have it, a list of helpful objects that you can tap into to add some extra useful stuff into your programs.

Now how about I give you some of the most common uses for each of these objects? I think that would be super helpful for you.

JavaScript Document Object

As mentioned, the document object is used to interact with elements in your HTML pages. The most common use (that I’ve seen) for the document object is to retrieve elements from the page and tinker with them.

Let’s take a look at a basic HTML page and then modify its contents when you push a button.

<html>
  <head>
    <title>Simple Page</title>
    <script type="text/javascript">
      function spiceItUp() {
        var paragraphElement = document.getElementById("aParagraph");
        paragraphElement.style.backgroundColor = "yellow"
		paragraphElement.style.fontSize = "24px";
      }
    </script>
  </head>
  <body>
    <p id="aParagraph">
      Here's some text. It's very boring. But something tells me we're going to spice it up!
    </p>
    <input type="button" onclick="spiceItUp()" value="Spice it up!"/>
  </body>
</html>

Go ahead and try copy/pasting the code above into your own HTML file and open it in a browser. You’ll see something interesting happen when you click on the “spice it up” button.

The part to note here is that we were able to modify the look & feel of the text by using the document.getElementById() object and function to assign that paragraph element to a variable called paragraphElement. Then we took the paragraphElement and changed its style a bit. Powerful stuff!

JavaScript Location Object

The location object is typically used to just forward a user onto a different URL. Let’s create a simple webpage that forwards you to Google.com when you click on a button.

<html>
  <head>
    <title>Simple Page</title>
    <script type="text/javascript">
      function goToGoogle() {
        window.location.href = "http://google.com";
      }
    </script>
  </head>
  <body>
    <p id="aParagraph">
      I'm just a simple boring webpage... until you click that button!
    </p>
    <input type="button" onclick="goToGoogle()" value="Go to Google!"/>
  </body>
</html>

Go ahead and copy/paste this code into your own HTML file.

You’ll notice that there’s a button on the screen that says “Go to Google!”. Now when you click on it, it’ll use the location object (located in via window.location) to send you off to Google.

JavaScript History Object

The history object is really easy to comprehend. I don’t think I’ll need to give you a full example like I did above. I have confidence that you’ll figure out how to make use of its functions.

As a guide, I’ll show you how to invoke its functions:

// If you want to send the user BACK to a previous page
window.history.back();
// If you want to send the user FORWARD to a page they were visiting
window.history.forward();

JavaScript Screen Object

The screen object is used to get the width and height of the screen of your user’s device. This is most useful when you’re trying to figure out how to display content on their screen.

With the advent of mobile devices, it’s becoming more and more “polite” to give your users a nice viewing experience when they visit your website on a mobile device. Using the screen object will tell you exactly how big (or small) their device’s screen really is.

<html>
  <head>
    <title>Simple Page</title>
    <script type="text/javascript">
      function getScreenSize() {
        alert("Height: " + screen.height + ", Width: " + screen.width);
		alert("Height without taskbar: " + screen.availHeight + ", Width without taskbar: " + screen.availWidth);
      }
	  
    </script>
  </head>
  <body>
    <p id="aParagraph">
      I'm just a simple boring webpage... until you click that button!
    </p>
    <input type="button" onclick="getScreenSize()" value="What's My Screen Size?"/>
  </body>
</html>

Go ahead an click here to see how big your screen is.

JavaScript Navigator Object

Finally we come to the navigator object, which is used to determine intimate details about the browser that you’re using.

This can be used to change the way a webpage looks or acts depending on the type of browser that’s being used.

I know that one practical use of the navigator object that I used a while back was when I did some HTML5 programming (back when it wasn’t as well supported as it is now). I wrote code that essentially only worked in a Chrome browser, so I would use the navigator to determine the type of browser my users were using, and display a warning message if it wasn’t a Chrome (webkit) browser.

Here’s some code that will break down the browser’s details:

<html>
  <head>
    <title>Simple Page</title>
    <script type="text/javascript">
      function getBrowserInfo() {
        alert("Your Browser's code name: " + navigator.appCodeName + "\n" + 
		  "Your Browser's app name: " + navigator.appName + "\n" + 
		  "Your Browser's product name: " + navigator.product + "\n" + 
		  "Your Browser's platform: " + navigator.platform + "\n" + 
		  "Your Browser's user agent: " + navigator.userAgent
		);
      }
    </script>
  </head>
  <body>
    <p id="aParagraph">
      I'm just a simple boring webpage... until you click that button!
    </p>
    <input type="button" onclick="getBrowserInfo()" value="What Browser am I Using?"/>
  </body>
</html>

Try that code out for yourself and see what details may surprise you about the type of browser that YOU are using!

In Summary

JavaScript provide a great library of built-in objects that can be used to your programming advantage.

You never know when you might come to a situation where you’ll need to determine the type of browser someone is using, or when you might need to dynamically modify an element on the page.

So be sure to make yourself familiar with these objects and their many uses, it’ll make you a far better JavaScript programmer.

And hey, speaking of being a better JavaScript programmer, be sure to type your email into the box below, you’ll get a special freebie that will be sure to enhance your programming skills.

{ 2 comments }

Null vs Undefined in JavaScript

null vs undefined in javascriptOne thing that threw me off when I started learning JavaScript (with a background in Java) was the fact that JavaScript has both undefined and null as possible values for a variable.

In Java, all we have is just null which means that the variable has no value.

So when I saw this additional value of undefined in JavaScript, I was confused… what did it mean?

Undefined Means “Nothing”

When a variable has the value of undefined it means two things:

  1. A variable has been declared
  2. The variable that has been declared has not yet been assigned ANY value whatsoever

An example of this in JavaScript would be as follows:

var person;

So as you can see, I’ve declared a variable, but I haven’t assigned a value.

Now if I were to inspect that person variable to see what value it contained, you’d see that it says “undefined”.

var person;
alert("The person variable has the value: " + person);

Here’s what the output of this code would be:
null vs undefined img 1

Now it’s also interesting to note that when we inspect the type that is assigned to our person variable, we’ll get the type undefined. This makes sense if you remember reading this article on the different data types in JavaScript.

Okay, fair enough then right?

undefined means that there’s nothing assigned to our variable… so then, what the heck does null mean?

Null is a Place-holder for Nothing

In JavaScript null means that you’ve intentionally assigned a value to your variable, and therefore you’re intentionally assigning the value of nothing to your variable.

You can think null like a place-holder, meaning that the variable has nothing inside of it, but you intend on assigning it a value later.

The interesting thing to note about assigning null to a variable is what type JavaScript gives to a variable that has been assigned the value of null. Let’s take a look:

var person = null;
alert("The person variable has the data type: " + (typeof person));

Here’s the result:
null vs undefined img 2

What!?

The type of our person variable is object?

Believe it or not, this is a bug in JavaScript that they’ve just sort of “leaned into” and stuck with over the years. It’s part of the way the JavaScript engine works and if they changed it now, it would likely cause some side-effects to a lot of code out there on the interwebs.

The common justification for this bug is that when you’re using the value of null for a variable, it’s because you’re using it as a place-holder for an object that will be assigned to this variable later.

Not the greatest justification, but that’s just how the cookie crumbles in this case.

In Summary

The value of undefined is assigned to any variable that has not yet been assigned a value.

The value of null can be assigned by YOU if you like, and it represents a lack of a value (aka. nothing!)

Clear as mud?

Good!

No go and put your email address into the box below so I can send you a free goodie that you’ll love. You’ve already read down to the bottom of this article, so I know you’ll love the stuff I’ll send to you.

Boo yah!

{ 0 comments }

Objects in JavaScript

Objects in JavaScriptAs we all know, JavaScript is an object oriented programming language, but we haven’t yet gone into detail about how objects work in JavaScript.

Today, we’re going to change that!

You see, Objects are by far the most powerful data type that exists in JavaScript and I’m about to show you why.

JavaScript Object Declaration

As you’ve seen briefly in other articles on this site, you’ve seen how to declare a variable that will be backed by the Object data type, kind of like this:

var objExample = {};

You can see that we use the open/close curly brackets to declare a variable in JavaScript that will be backed by the Object data type. I say that it will be “backed by the object data type” because you can’t explicitly declare a variable as an object in JavaScript due to its dynamic typing.

In any case, this is a pretty mundane example of how to create an Object in JavaScript, so let’s get more complex shall we?

Assigning Properties to Objects

The real magic with Objects in JavaScript is that you can assign properties to objects.

These are basically just name/value pairs (just like a Map in Java).

Let’s go ahead and create a Person object in JavaScript:

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

Now what I’ve done here is I have created an object called Person with four properties:

  • firstName
  • lastName
  • age
  • gender

I have created this person object using something called JSON, which stands for JavaScript Object Notation. So everything you see from the opening curly bracket to the closing curly bracket is JSON.

Note: my JSON isn’t entirely valid, as the names of the properties should be strings, and I didn’t use double quotes, but that’s just because JavaScript doesn’t complain and knows how to handle the code. So really my only excuse is that I’m lazy and don’t want to type out a bunch of double quotes. For the sake of completion, here’s what the declaration would look like with completely valid JSON:

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

You’ll see here that each of the names of the properties are now wrapped in double quotes.

If ever you want to validate your JSON strings, then I’d recommend a site like JSONLint. It allows you to copy/paste your JSON string into an input box and hit a “validate” button to check your code. It will then show you errors if your JSON isn’t properly formed.

Declaring Objects Without JSON

Believe it or not, JavaScript also allows you to create objects without using the full JSON syntax. You’ll still need to declare a variable with the open/close curly brackets, but then you can start populating the Object’s properties with the dot property syntax.

Here’s an example of how to populate an object’s properties with the dot property syntax:

// first we declare the variable using the most basic JSON string there is
var person = {};

// now we can start adding properties using the dot property syntax
person.firstName = "Trevor";
person.lastName = "Page";
person.age = 32;
person.gender = "Male";

And now we have created an Object without using a whole bunch of JSON text!

Note: there are subtle differences between these two objects, but we won’t dive into those crazy details until we talk more about an Object’s prototype in a later lesson.

Creating Methods in Objects

There’s a great article on mozilla.org that sums up what Objects are in an elegant way:

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name and a value. A property’s value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.

So what I want to talk about now is creating property methods.

Remember that an Object can have properties, and those properties are comprised of a name and a value. For example a property name could be "gender" and a value could then be "Female". Pretty simple right?

But with the addition property methods, we can have a the value of a property be a function!

Let’s add a function to our person object. As always there are two ways to do this, you can either use JSON or the dot property syntax. First let’s take a look at the JSON syntax:

var person = 
{
  firstName: "Trevor", 
  lastName: "Page", 
  age: 32, 
  gender: "Male", 
  goToWork: function () 
  {
    alert(this.firstName + " is now going to work");
  }
};

Now let’s take a look at the dot property syntax:

person.goToWork = function () {
  alert(this.firstName + " is now going to work");
}

Note: With the JSON code, we needed to add the goToWork function in with the original definition of the object, so there seems to be a lot more code when using the JSON syntax… but this code will be reduced once we talk more about the subject of prototypes.

Okay, so now that we’ve added a function as a property to our person object, all we need to do to “invoke” the function is this:

person.goToWork();

Once we run the code above, we’ll get an alert saying "Trevor is now going to work".

In Summary

We’ve only hit on a few key points with respect to JavaScript Objects and there are more tutorials to come that will cover other aspects of programming with Objects in JavaScript.

But so long as you can remember that Objects have properties, and properties are made up of name / value pairs, then you’ll be in a great spot to keep on learning how to use Objects in JavaScript.

OH! Hey by the way, don’t forget to put your email address in the box below for some free goodies. Seriously, I’ll send you something very relevant to what you’re learning now directly to your inbox. Check out the details in the box below.

{ 0 comments }

JavaScript TypeOf Keyword

We know that JavaScript is a dynamically typed language, but remember, this doesn’t mean that JavaScript is void of types.

JavaScript absolutely has types that back its variables, we’re just sort of “abstracted” out of that process by its magic and wizardry. Okay it’s not magic, it’s just code, but it can seem like magic at times right?

So the real question here is, how can we determine the type that is assigned to any given variable?

Determining a Variable’s Type in JavaScript

Thankfully, JavaScript makes it easy to determine the type that backs any of your variables.

It’s called the typeof keyword.

Here’s an example of how it’s used:

  var myVariable = "What's my type?";
  alert("myVariable's type is: " + (typeof myVariable));

Here’s the result:

typeof_keyword_javascript

There you have it! The type of myVariable is string.

So to determine any variable’s type in JavaScript, you just need to put the typeof keyword before a variable and it will return a string that describes the variable’s type.

Examples of typeof Keyword

var anObj = {someProperty: "Just an example"};

if (typeof anObj == 'string')
{
  alert("Our variable is a string");
}
else if (typeof anObj == 'object')
{
  alert("Ladies and gentlemen, we have an object!");
}

In Summary

There’s really not much to the typeof keyword as you can see. It’s quite straight forward to use and it just “works” like you’d imagine it would. Phew!

What may help you out is to know the different types that can be assigned to any given variable, so if you’re fuzzy on the list, just check out this article to help refresh your memory.

And hey, don’t forget to sign up for our mailing list below. I’m always giving out awesome free stuff and get such great feedback from my students with respect to how much they love what I send out. So it’s likely worth your time and I promise never ever ever ever to sell or give away your information to anyone, that kind of business is just too sleazy for me!

{ 1 comment }


Showing data to users and getting data from users is a pretty fundamental task in programming.

If you come from a Java programming background, you’re probably used to using the console to display information to the user as well as using something like the Scanner to retrieve data via the console as well. But with JavaScript it’s a lot more straight forward.

You see, JavaScript offers not only console logging, but also a simple means by which to display messages and get inputs from the users.

This is what we’ll be diving into today. First off, let’s start with the easy stuff: displaying messages!

How to Display Messages / Alerts to Users with JavaScript

Displaying messages is as simple as using the alert function.

Here’s a simple example of how to display an alert message with JavaScript:

alert("This is a test message");

If you’d like, you can go ahead and click here to see what that alert message looks like.

And it’s really as simple as that!

As a rule of thumb, I would avoid overusing the alert function though, as users will get annoyed by having to click on “OK” over and over again.

How to Get Data from Users

Getting data from users using JavaScript is also very easy.

There are two functions you can use:

  • prompt
  • confirm

JavaScript Prompt

The prompt function is used to get textual or numerical (or both) data from the user. It will just put up a dialogue box on screen with any message you’d like to display along with a text box allowing them to input anything they like.

Here’s an example of a prompt:

  var response = prompt("Hey there, what's your name?");
  alert("You typed: " + response);

Notice that we use a variable (called response) to store the input that the user types into the prompt.

If you’d like, you can go ahead and click here to see what that prompt looks like.

JavaScript Confirm

The confirm function is used in a very similar fashion as the alert function, but with one big difference. The confirm function will show an alert box with two options “OK” and “Cancel”.

Here’s an example of a confirm popup:

  var response = confirm("Hey there, do you want to learn more about JavaScript?");
  alert("Your response was: " + response);

Notice that we use a variable (called response) to store the choice the user makes (either “OK” or “Cancel”). When the user clicks “OK” the response variable will be true, if the user clicks “Cancel” the response variable will be false.

If you’d like, you can go ahead and click here to see what the confirm popup looks like.

In Summary

Thankfully this kind of user interaction is not rocket science and is fairly easy to follow.

If you’re wondering if there are other methods for retrieving data from users in JavaScript, the answer is “Sort of”.

You see, JavaScript isn’t really meant to be the primary source of showing or collecting input from webpage users. HTML is best used for these tasks.

So a typical scenario is to use HTML input tags to gather input from users and then you JavaScript code to validate that the data is valid before sending it off to a web server!

But if you’re in a bind and need a quick way to show or get data from your users, then look no further than JavaScript and the three functions we talked about today.

PS. Don’t forget that I’m always giving away awesome free stuff when you join our email list. I also don’t sell or give away your email addresses to ANYONE, I never have and a I never will! So be sure to check out what free goodies I’m giving away by filling out the form below :)

{ 0 comments }

JavaScript Assignment #1: Number Guessing Game

Functionality

Welcome to your first JavaScript assignment. Your job in this assignment will be to create a game where you’ll need to guess a number between 1 and 100 (inclusive) within 6 attempts.

With JavaScript, in order to get an input from a user, you’ll need to make use of the prompt function.

Here’s an example of how you would prompt someone for information using the prompt function.

var aNumber = prompt("Please guess a number between 1 and 100");

This will show a dialog box on the screen allowing the user to enter some input. The result of what the user types in will (in this case) be stored in the variable aNumber.

The program should first randomly pick a number between 1 and 100 and then prompt the user to guess the number. It should also show the user how many guesses they have left:

javascript assignment 1 screenshot 1

When you guess a number, the application should do some validation on the input. It should:

  1. Validate that the inputted value is indeed a number (please see appendix for an explanation of how to do this)
  2. Validate that the inputted value is between 1 and 100 (inclusive). This means that the number 0 is an invalid input, but the value 1 is valid. Also the value 101 would be invalid, but the number 100 would be valid.


If the value entered into the prompt is invalid, then you should prompt them again asking to input a valid number like so:

javascript assignment 1 screenshot 2

Once the inputted value is deemed valid, the application should compare your guessed number to the one originally picked.

If your number is larger, then the program will alert you with a message saying “You need to guess a smaller number.

If your number is smaller, then the program will alert you with a message saying “You need to guess a larger number.

And if you are able to guess the number, then the program will say “Congrats! You got it! My number was: [randomly generated number]

Note: be sure to replace the [randomly generated number] placeholder with the actual number that was chosen by the computer at the beginning.

If after 6 attempts the user was NOT able to guess the number correctly, you should display an alert like so:

javascript assignment 1 screenshot 3

Note: be sure to show the actual number that was randomly generated by the program, the number 21 displayed above was just the number that was picked when I ran my program.

Appendix

Validating that a value is a number

In order to validate that a value is indeed numeric, you can use a function called isNaN(aVariable). This function takes a single parameter. This parameter will be checked by the function to see if it is a number or not.

If the variable is a number, it will return false. If the variable is NOT a number, it will return true.

For example:
isNaN("test") returns true
isNaN(10) returns false

{ 0 comments }

Importing JavaScript into HTML via Script tag

Up to this point we haven’t talked about the elephant in the room!

And that’s the fact that we’ve been talking about JavaScript for quite a while now, but we haven’t yet discussed how to actually USE JavaScript inside of an HTML page.

Well, no time is better than the present right? Let’s talk about JavaScript and HTML.

How to Link HTML and JavaScript Together

As I just mentioned, you’ve already seen many examples of JavaScript syntax, but we haven’t seen the link between an HTML page and the JavaScript code.

The link between them is pretty straight-forward, you just need to know that there are two ways to link your JavaScript code to your HTML pages:

  1. Importing an external JavaScript file into your HTML page
  2. Embedding JavaScript code directly onto your HTML page

Now that you know there are two ways to link your JavaScript to your HTML, let’s take a look at each approach.

Importing JavaScript into an HTML Page

If you happen to have some JavaScript code stored in a file (like we saw in the last article on debugging in JavaScript) then there’s a simple way to “import” this JavaScript code into your HTML page.

Let’s first assume that we have a basic HTML page like so:

<!DOCTYPE HTML>
<html>
  <head>
    <title>A Simple HTML Page</title>
  </head>
  <body>
    <h1>My HTML Page</h2>
  </body>
</html>

Secondly, let’s also assume that we have a JavaScript file that’s called “Debugging_Example.js” and we’d like to include it into our HTML page above. In this case, we’ve already seen this JavaScript file in the last article on debugging, and we know that it is stored in the following URL: https://howtoprogramwithjava.com/wp-content/uploads/2015/07/Debugging_Example.js

Note: If you like, you can even click on it and see the contents of the JS file in a new tab

Okay, so now we know where our example JavaScript file exists, where do we go from here?

Well, in order to import this JavaScript file into our HTML file, we just need to use a <script> tag with a src property that points to the file itself.

Here’s what that script tag would look like:

<script type="text/javascript" src="https://howtoprogramwithjava.com/wp-content/uploads/2015/07/Debugging_Example.js"></script>

SUPER IMPORTANT NOTE: When using the script tag, it is mandatory that you use the closing </script> tag just as it appears. Don’t try to use the “short-cut” approach like this <script type="text/javascript" />. This will cause issues and will likely end in your script NOT being imported at all.

Alright, having said that, let’s put all of this code together and import this JavaScript file into our simple HTML page!

It’s usually recommended that you put your script tags into the head area of your page like so:

<!DOCTYPE HTML>
<html>
  <head>
    <title>A Simple HTML Page</title>
    <script type="text/javascript" src="https://howtoprogramwithjava.com/wp-content/uploads/2015/07/Debugging_Example.js"></script>
  </head>
  <body>
    <h1>My HTML Page</h2>
  </body>
</html>

And voila! You’ve now successfully imported the “Debugging_Example.js” file into your simple HTML page.

Pretty simple to understand I hope.

Embedding JavaScript Code in Your HTML Page

There is also a second way to include JavaScript code in your HTML files, and that’s by directly embedding the JS code itself.

This method is nearly identical to the one above, and thus the same rules from above apply here. You still need to use the proper closing </script> tag when embedding JavaScript code.

The only difference when embedding JavaScript code is that you don’t specify a src property, as you’re not importing the code from an external file, so there’s no purpose to trying to specify the source of the code right?

Here’s what embedding our “debugging example” code would look like:

<!DOCTYPE HTML>
<html>
  <head>
    <title>A Simple HTML Page</title>
    <script type="text/javascript" >
      console.log("The words you're seeing here are coming from a JavaScript file that I've loaded");
      console.log("You'll be able to debug this JavaScript file in your browser");
      console.log("For the sake of seeing debugging in action, let's use a FOR loop to count to 10");
      
      for (var i=0; i<10; i++)
      {
        console.log(i);
      }
      console.log("And now we're done counting, hope you enjoyed it!");
    </script>
  </head>
  <body>
    <h1>My HTML Page</h2>
  </body>
</html>

Boom! You've just learned how to directly embed JavaScript code into your HTML pages.

When to Import and When to Embed

So you're probably wondering when you should use either of the two options for including JavaScript code on your HTML pages.

And the answer is also pretty simple.

Generally speaking, it's best to separate your JavaScript code from you HTML code.

This means that it's usually a best practice to create separate JavaScript files (just like our "Debugging_Example.js" file) and import them rather than embed them.

When you embed a LOT of JavaScript code, it can get a little bit hard to follow along with the HTML file. So you should try to always favor importing over embedding.

In Summary

In order for your HTML files to make use of JavaScript code, you'll need to include the JavaScript code IN your HTML files in one of two ways.

Either you import the code from an external JS file, or you embed the JavaScript code right into your HTML page.

Both approaches will get the job done, but you should try to favor importing your code from an external file, as it's best to separate your HTML code from your JavaScript code for easy readability.

Oh! And don't forget, we're always offering SWEET stuff in the email signup form below. So if you haven't already, be sure to check out what freebies we're offering and sign up below.

{ 0 comments }