|

JavaScript Types and Objects Tutorial

JavaScript Types and Objects Tutorial

Getting familiar with the various types and objects in JavaScript is going to be very important before we jump into other more advanced features of the language. Soon we’ll be looking at the DOM or Document Object Model, functions in JavaScript, testing and debugging, and much more. Before we get to that point however, we need to have a firm grasp of the fundamentals of the language. Along with some of the prior articles on JavaScript here at Vegibit, this tutorial is going to make sure we’re up to speed on these concepts, let’s jump in!


Creating JavaScript Arrays

We’ve covered how to make variables and store a value within them, it’s pretty easy. Recall we simply use the keyword var, followed by a name, and assign a value to it. We can store whatever we like, but it is only one thing that can be stored in the variable. Arrays are different in that they allow us to store many values.

Here with this single line of code, we create a variable that can store multiple things inside of it. Essentially, we are assigning an empty array to the variable named manyvalues.

We can now populate that variable in many different ways. Let’s check out some of the ways we can do this.

Assignment By Index

We can explicitly assign a value to any index we choose.

Wow! Check that out Henry! We can put whatever we like into the various containers of our array. We can put a string, number, boolean, function, object, or whatever. Our array will happily contain the values we assign.

We can easily set and get by index. We have set some values by index to our array, now let’s retrieve them:

Get Your Array Shorthand On

The prior section shows how to create arrays, and it’s a bit of the long hand version. We can shorten things up and make an array with easier syntax. All we have to do is use the square brackets, and populate the array with the values we want like so. Here is how we can do that same array with the shorthand notation:

This produces the exact same result, and it saves us a bit of typing. Note that due to JavaScript essentially ignoring whitespace, we can format the syntax as we did here to make it a little more readable. This is the same example again with all spaces removed. You can use whatever format you feel comfortable with, as long as the syntax and delimeters adhere to the JavaScript rules.

JavaScript Arrays are Objects

Since JavaScript Arrays are actually Objects, we can also create an array using a pseudo classical style. I say pseudo classical, since JavaScript doesn’t actually have classes. Most likely you have programmed in other languages and are somewhat familiar with the idea of objects being an instance of a class. JavaScript is not a classical language, it is a prototypal language. Which is to say it is going to drive you absolutely bananas trying to figure out what objects come from where! Actually, what it means is that objects inherit directly from other objects, and it is a bit confusing. In any event, we are talking about Arrays! Here is that classical looking Array assignment:

Array Properties and Methods

Since arrays in JavaScript are actually objects, it also has some built in properties and methods. These are the characteristics and actions which can be used with the array. Some examples are in order.

Array.length

The length property is a very handy built in property of the JavaScript object. It makes finding the length of an array a real breeze. Like a wonderful Bahamma Breeze in fact. As you can see in the following example we take a few steps to demonstrate this. First we populate an array named manyvalues with three different strings. Second, just to show that it actually works, we complete a console.log of the length property. We can see it’s length is 3! Remember, the highest index is actually 2, but our array length is 3 since arrays are zero based. We then jump forward a little and show how you can use this convenient property in iterating over data in the array using a for loop:

As we can see in this output, having this gives us the ability to have fine tuned control over the number of iterations in our for loop.
javascript array length

JavaScript Array Functions

JavaScrip Array Objects also have methods. Methods are functions that belong to an object. The syntax for calling a method in JavaScript is by using the dot . operator like this:

The camel case is not required but only used to display the object portion and method portion of the expression more clearly.

Array.reverse()

This nifty built in method takes an array, reverses the contents of said array, and returns the resulting new order. Recall our manyvalues array, let’s go ahead and reverse it!

javascript array reverse

Array.sort()

We can sort arrays easily using the built in sort method:

javascript array sort

Array.pop()

Popping a value off of the end of an array is useful in many instances. Here is an example of using .pop()

javascript array pop

The Mozilla Developers Network has heaps more information about JavaScript Arrays, feel free to check them out.

JavaScript Arrays are Very Common

You may be wondering what the purpose or usefulness of arrays in JavaScript is. Arrays are very common and are used frequently in operating on the DOM or Document Object Model. We haven’t covered the details of the DOM as of yet, but we will. Here is an example of how an array in JavaScript is useful to us when working with the DOM:

document.getElementsByTagName()

The method .getElementsByTagName() is a method that reaches into the DOM and returns all instances of the particular tag that you specify. If you pass the method a p, it will return all paragraphs. If you pass the method an a, it will return all anchor tags on the page. This works for any HTML tag. You can even pass the wildcard asterisk * as a parameter, and the method will return *all* occurrences of all HTML tags on the page. It returns these items as an array!

This snippet above scans through all HTML elements on the page, and places them in a variable called aptly, elements. Now depending on what page you run this snippet on, you will get a different result. When I try this experiment while on the gawker.com home page, I show 1723 elements as the length of the array. Pretty Cool! We’ll usually be using this in a more refined way like grabbing all p tags or all div tags.

Wrapping up with arrays, we’re going to be using them all the time in JavaScript. Arrays are dynamic, in that they are easily modified and read, they are zero based just like most other programming languages, they are easily identified via the square bracket notation, and they have a number of useful built in methods to help us with computing the data which they may contain.


JavaScript Numbers

Working with JavaScript Numbers is a little different than other programming languages. Experienced programmers will look at a number in JavaScript and wonder, is it an integer, a float, a double, what is it? Well in JavaScript, there is only one number type. JavaScript uses 64 bit floating point numbers, no matter what. So if you see a number, it is essentially floating point, and you don’t have to worry about type conversion between integers and floats like you would elsewhere.

When we specify numbers, no special convention is necessary, all of the following are numbers in JavaScript:

Addition vs Concatenation in JavaScript

One of the things that can sometimes be a little confusing in JavaScript is the + plus sign operator. As we would think, the + sign will happily add two numbers together just fine. Let’s test it:

Yes! This logs out the number 2000, just like we would expect. So the 500 and the 1500 are real numbers, as they are not surrounded by quotes. What if they were? Let’s see:

Well, this is a very different result! The reason, is that in the second example, the numbers are actually of data type string. When we use the + sign with strings, it simply concatenates the two items together. Just like in PHP where you can combine two strings together with a dot . operator, in JavaScript we use the + plus operator.

So what happens if you try to do this when one of the variables is a string, and the other is a number? We can test this now:

In this instance, we get the same result as if they were both strings. That is because when using the + operator, if one of the operands is a string, the whole expression is treated like a string. Let’s take it a step further and multiply the two operands together and see what happens:

In contrast to the + operator, the * operator will assume both 500 and ‘1500’ are both numeric, and the product comes out to 750000. Well. Let’s throw some real challenges to JavaScript. We’re now going to take 500 and multiply it by chicken. Let’ go:

There it is. The dreaded NaN, the Not a Number. NaN is like a mythological creature, born of legend, highly misunderstood, infinitely confusing and frustrating. NaN has always felt slippery to me, it’s meaning and use is tricky. Often times, when we see NaN, it means something went wrong somewhere with type conversion. While weak typing is great for its expressiveness and ease of use, it can lead to sloppy code, so be careful! Thankfully, we do have the function isNaN() to help in our JavaScript code:

This way you can be sure your numbers are actually numbers when using them in your JavaScript programs.

The Math Object in JavaScript

Finally in the numbers section, we’ll talk about the handy Math Object in JavaScript. So what good is this Math Object you ask? Well, let’s try a few things with it in some code.

This is just a small sample of the many methods available to you of the Math Object in JavaScript. To learn more about the additional ones for your use and pleasure, simply visit the Mozilla Developers Network and have a ball.


JavaScript Strings

Now we get to take a close look at strings in the wonderful world of JavaScript programming. When dealing with the web, strings are literally everywhere, and we’ll be working with them no matter what language we are currently making use of. Enough about that however, we’re talking JavaScript Strings here so let’s check it out.

Using Quotes to Create Strings

Strings always live inside quotes. They can be double or single, but they can not be interchanged. Meaning, don’t mix your quotes.

This works

This does not work

This does not work

This works if we simply escape the quotes inside of quotes

Strings also have Properties

Just like we saw with the Array Object we already examined, strings in JavaScript also have properties and methods. Once we place a string inside of a variable, we can then access some of those properties and methods. Of course we’ll look at some code:

Just like the Array Object, we have the length property to tell us right away how long the string is. In a sense, the string is merely an array of characters, so it’s not a huge leap to get the idea that the length property works on both.

JavaScript String Methods

I’m guessing you are beginning to see a pattern here 🙂 Yes grasshopper, strings also have methods, and they are quite useful in fact. Let’s check them out:

JavaScript String Comparison

There will be times that we need to complete some string comparisons in our JavaScript and there are a few points to be aware of. Strings are case sensitive in comparison so 'You Rock' does not equal 'you rock'. If you need to perform string comparison and not worry about the case, simply apply either .toLowerCase() or .toUpperCase() to both strings first then compare:

There are a lot more about JavaScript string methods to know, so when in doubt, just head over to the MDN, and have a look.


Working with Dates in JavaScript

Unlike some other programming languages, JavaScript does not have a really high number of objects that we need to know in order to work with the language. We’ve taken a look at the Math, Array, and String objects. We’ll now look at the Date Object.

JavaScript Get Methods for the Date Object

There are a lot of handy get methods that come with the Date Object. This makes it easy to get the month, or get the day, or get the year. Let’s see how we do it:


JavaScript Objects

If you read our Ultimate Guide to Object Oriented PHP, you have a good idea of the concept of objects. I have some news for you. Take every single thing you learned in that tutorial and throw it right out the window, because the JavaScript idea of objects is an entirely different animal! I’m not sure if it is better to learn the classical way of objects, or the way JavaScript does it, but one thing is certain – JavaScript is unique in it’s implementation of objects. The formal definition of an object in JavaScript is a mutable keyed collection. Say what?! It’s just a container of properties that have a name value pair, and you can read from it, write to it, or otherwise modify it as needed. It is a very flexible data structure. So flexible in fact, that if you are not careful in JavaScript, you will shoot yourself right in the foot. In fact, you are going to shoot yourself in the foot many times in JavaScript, get used to it. Once you do it several times, you’ll be on your way to making your programming skills that much better. In any event, let’s not worry about that, let’s start investigating JavaScript Objects.

Creating Objects

One of the ideas of Objects is to be able to group together data and actions that might be related. If we were working with a car in our JavaScript program, maybe we define some variables like so:

This is great, and it works just fine. These are related items however, and why not group them together in an object? Well, we can do that quite easily:

Now we have a car object, and we simply assign it properties as we choose. There is that mutable behavior it has. Your object needs a value or property associated with it? Simply use the dot . syntax and assign as needed. Your properties magically come into being, just like that.

Shorthand Object Creation

The prior example is one way to create an object in JavaScript. There is an easier way to do this and achieve the same result:

Having this all on one line might be a little tricky to read. If your IDE has a beautify or prettify option, you can use it to make your code more readable like so:

To JavaScript, it’s the same thing. To us humans, the second version is more readable.

JavaScript Methods of Objects

Now that we know how to create objects easily, and give them properties, how can we make them do things? Well, we can place function inside of objects as well. Let’s create two different cars, and make a function that can provide information about the given object:

Note that we only had to define the carDetails() function once, yet it works on both of the different objects! How does this happen? What is happening here is a the function is making special use of the this keyword. this informs the program that we are dealing with this particular instance of the object. This is how each object is able to associate the correct data to it.

Wrapping Up The JavaScript Types and Objects Tutorial

This has been a great overview of the basic types and objects that you will need to get yourself up and running confidently with small JavaScript applications. I recommend researching the works of Douglas Crockford, David Flanagan, John Resig, and Bear Bibeault if you have a desire to dig further in with JavaScript!