Javascript 101: Introduction to Datatypes

As promised, this is the first post of a longer Javascript 101 Series. Luckily, as Javascript runs directly in your browser, there are several options for you to write your first lines of javascript without having to install an entire local development environment on your machine.

A site that has been extremely helpful for me during my first steps with Javascript has been repl.it. The website allows you to write your code and see the output right next to your code, save shareable links and doesn’t require any kind of registration to do so. While it is possible to also run javascript code directly in the console of your browser, I’d recommend to work with repl.it for the first parts of the tutorial due to its simplicity and the fact that the browser console and developer tools require an entire introduction by themselves, which will follow in a later post.

Now that we are all set, we can get started with the actual topic of this post. I highly encourage you to not only read through my examples, but actively write some code and variations of the given examples.

Data Types in Javascript

When we speak about data in the context of computer programming, most people think about long rows of ones and zeros running across the screen. While all data processes in computers are indeed based on a binary system of ones and zeros, we don’t have to worry about translating our words, decimal numbers and other data structures into binary code. Our browser will take care of that. Working with data in Javascript is much less intimidating. To give you the right tools for writing great applications, Javascript offers 5 distinct data types. If Javascript is not your first language, these data types will be very familiar to you.

Numbers

The first data type we will look at is numerical data. When speaking about numbers in programming you will most likely come across two terms that are being used to describe numbers: Integers and Floats. In general, Integers refer to whole numbers such as 245982, while Floats are numbers with a decimal point such as 4.2842. Note that depending on where on this planet you live, you might be used to writing numbers not with a decimal point but with a comma like 4,282. In general, you always want to use a dot for using floats in programming.

Let’s start writing some basic mathematical expressions in Javascript. The grey text behind the example code is a comment. It doesn’t have any effect on the code and is meant to provide an explanation to the code examples. Try and enter some of those examples into repl.it and click on run. On the right side in green you will see the result of your calculation.

10 + 18 // addition, equals 28  
10 - 2.5 // subtraction, equals 7.5  
28 / 2 // division, equals 14  
23 * 3 // multiplication, equals 69  
22 % 10 // modulus, equals 2  

So far so good. These mathematical symbols are referred to as operators. One that you might not have seen before is %, the modulus operator. This operator will divide by the second given number 22/10 and then return the remainder 2. Besides those operators there are 4 more, which will help you to compare values against each other:

5 > 3 // 5 is more than 3, equals true  
8 < 9 // 8 is less than 120, equals true  
7 < 2 // 7 is less than 2, equals false

5 === 5 // 5 is equal 5, equals true  

Again, nothing mindblowing happening here. One thing that might seem weird is the use of three equal signs to compare the equality. This is due to the fact that a single equal sign is used to declare variables (more on that later) and two equal signs are a less strict comparison than the three equal signs. For most cases using three equal signs for comparison is the way to go. You might be tempted to just enter two equal signs and call it a day. This might work in 80% of the cases, but believe me - you don’t want your code falling into the last 20% resulting in gibberish because you’ve been too lazy to write a third equal sign. Ok?

Booleans

As you have seen when using the comparison operators, we did not receive a number as response to our expression. What we received was either true or false - a boolean value. The name did not originate from the spooky super mario character, but from the mathematician and creator of boolean logic, George Boole. While learning about boolean algebra can keep you busy for quite a bit, all you need to know for now is that boolean values can be either true or false. This comes in handy if we want to check for conditions (is a user logged in, did a button press occur, did our player gain 500 coins etc). We could also use a number to express these states and set it to 1 or 0, depending on the state of our program, but using boolean values is cleaner and prevents the data from having any other value, while a number could potentially become 2 or 3.

Strings

As written previously, Javascript doesn’t require us to type in 1’s and 0’s to make sense of our data. Strings allow us to easily work with words such as "dog" or "cat" in our programs. Strings can also be entire sentences or paragraphs "Remember to buy 5 litres of milk". Even HTML elements can be contained in a string: "<div class=’user-icon’></div>". To define a string, you need to add two quotation marks " around the entire group of words.

When working with strings, we can use the additive operator as well as comparison operators:

"dog" + "cat" // joining strings, equals "dogcat"
"12" + "18" // joining strings, equals "1218"

"c" > "a" // comparing position in alphabet (a is the lowest value, z the highest), equals true
"apple" > "bug" // the first letter dominates all other letters, equals false
"ac" > "ab" // if the first letters are equal, the next letter will be compared, equals true
"acz" > "acy" // if the second letters are equal, the third will be compared… and so on, equals true

"dog" === "cat" // compares strings, equals false
"dog" === "Dog" // uppercase letters matter, equals false
"cat" === "cat" // this will work, equals true
"15" === 15 // a string is a string, a number without quotation marks is a number, equals false

The last case is especially important and it’s a simple error that happens often to beginners. As soon as you declare a number as a string by adding quotation marks around it, you will be unable to perform mathematical operations with it. Instead of addition, you will now join strings, leading to "12" + 18 returning 1218 instead of 30. This is even true if your second value is a number. Javascript will conveniently turn this value into a string for your operation. This way creating a string such as "I am " + 30 + " years old." becomes possible.

Arrays

Arrays are an incredibly powerful and versatile data type in Javascript. They are collections of strings, numbers and objects (more on objects in the next section). You create an array by adding two square brackets around a collection of items, separated by commas.

[43,24,54,65,22,19,22] // an array of numbers
["dog","cat","horse","fish","zebra"] // an array of strings
[120, "icecream", 42.2321, "cow","chicken",12] // an array with mixed items

Every element in an array is associated with a numerical value, which is referred to as index. The index of the first element in an array is 0. The second element is accessed with the index 1, the third with 2 and so on. To access an array value by its index number, you add another pair of square brackets containing the index number after the array

[43,24,54,65,22,19,22][0] // accessing the first (0) index, equals 43
["dog","cat","horse","fish","zebra"][3] // accessing the fourth (3) index, equals "fish"
[120, "icecream", 42.2321, "cow","chicken",12][5] // accessing the sixth (5) index, equals 12

Mathematical operators won’t be of much help with arrays. You cannot combine arrays by using the + operator. You cannot compare the length of arrays by simply using the < or > operators. It is not possible to check for equality of two arrays by using the === operator. Don’t worry. This sounds pretty bad right now but luckily there are other ways to do all these things in Javascript. We will explore how to work effectively with arrays at a later stage.

Objects

The final datatype you need to know about are Objects. You will often hear about Objects in the context of Object Oriented Programming (short: OOP). Objects and OOP patterns can be found in several modern programming languages such as C++, Swift, Python and Java (not to confuse with Javascript). There has been an ongoing debate, if Javascript truly qualifies as an OOP language, as Javascript mixes the paradigms of different programming patterns. For now, let’s not dive too deep into this discussion but rather look at Objects as a data type. Objects are contained within curly brackets. Similar to arrays, they contain multiple values, which are separated by commas.

var myObject = {  
    name: "peter",
    age:34,
    hobbies: ["hiking","painting","programming"]
}

Two new things have happened here. First I’ve created a variable called myObject, which will contain our data. Don’t worry about variables for now, we will speak about them at a later stage. I’ve also added a linebreak after and before the curly braces to make things a bit easier to read. Javascript doesn’t care how you format your code, as long as the Syntax is correct. However, your colleagues will care, so make sure that you always try to write your code with readability in mind.

Unlike arrays, objects don’t order their values by index numbers, but by so called keys or attributes. In this case, our attributes are name, age and hobbies. Note that due to the lack of index numbers, there is no first or last attribute in objects. Even though we write hobbies as the last attribute here, we won’t be able to later access it as the last attribute of our object. Rather than using numbers, we will use our attributes to access the values directly.

var myObject = {  
    name: "peter",
    age:34,
    hobbies: ["hiking","painting","programming"]
}

myObject.name // equals "peter"  
myObject["name"] // equals "peter"  
myObject.hobbies // equals ["hiking","painting","programming"]  
myObject["age"] // equals 34  

As you can see, there are two ways to access our data. Either by writing object.attribute or object["attribute"]. The former is called dot-notation, while the latter is referred to as bracket-notation. There are some advantages to the bracket notation, such as being able to use variables as attribute names, but for now you can go with the notation that feels more natural for you. Unless you are working with variables, I’d recommend the dot-notation. Finally, Objects can also contain a collection of Objects:

var users = {  
    peter: {
        name: "peter",
        age:34,
        hobbies: ["hiking","painting","programming"]
    },
    sarah: {
        name: "sarah",
        age:30,
        hobbies: ["biking","running","design"]
    },
    jim: {
        name: "jim",
        age:26,
        hobbies: ["drinking","dancing","eating cake"]
    }   
}

In this case, we can access our values like this:

users.sarah.age // equals 30  
users.peter.hobbies // equals ["hiking","painting","programming"]  
users.jim.hobbies[2] // equals "eating cake"  

When we have accessed the hobbies of jim in the last example, we can add an index to directly access the right value in the array.

Objects offer a lot more than just storing data. There is prototypical inheritance, methods, constructors and other interesting concepts. But just like datatypes, it’s not rocket science and we’ll visit the ideas behind objects in a different post.

For now, you should feel confident in using integer and float numbers, strings, arrays and objects to store, modify and compare data values. In the next post, we will visit the concepts of functions, methods and variables, allowing us to dive deeper into data manipulation.

Until then, let me know if you have any questions in the comments.

Further down the rabbit hole