JavaScript Data Types - with examples

Learn about differen JavaScript Data Types and when to use them.

When programming with JavaScript you will more than likely be creating and using variables. When you define a variable it is given a data type. That is, the type of data that is being stored in that variable. In this article i’ll explain what JavaScript data types are available.

List of JavaScript data types

Here’s a quick list of JavaScript data types for your reference.

Primitives

String - letters, numbers and symbols Number - Either whole numbers (integers) or decimal Boolean - True or false

Complex

Object - Something that has properties and actions Function - A block of code that can be called from other parts of a program

Special

undefined - Given to a variable that has no data in it null - Nothing, emptiness, lonliness

Defining a variable in JavaScript

When you create a variable in JavaScript you don’t have to but probably should use the var keyword.

var myVariable = 42;

Did you see where I declared the variable’s data type? No? That’s because JavaScript did it for us, based on the type of data we put on the right hand side of the equals sign. This is different from some other programming languages where you have to specify the data type when you declare the variable. So do you need to think about data types when writing JavaScript code? Yes and no. No, because JavaScript handles this for you but yes because you can encounter odd behaviour if you’re not 100% what data types you are working with. We’ll look at some examples of these in a moment. First though, let’s run through the different JavaScript data types.

Primitive JavaScript data types

As the name suggests, primitive data types are those which are basic and fundamental to constructing JavaScript programs. These data types are also fairly common with other programming languages too.

String

A string is just a series of any combination of letters, numbers and symbols.

var string1 = "James Bubb";
var string2 = "password123";
var string3 = "https://www.juniordevelopercentral.com/";
var string4 = "21";

Notice how spaces are fine in string1 and symbols like : and / are OK in string3. Also, did you see how string4 only contains a number but it will still be considered a string as there are double quotes “ “ surrounding it. You can either use single or double quotes when declaring strings.

var string5 = "It's OK to use 'single quotes'";
var string6 = 'It is OK to use "double quotes"';

As you can see, sometimes you might want to use a single quote in your string so you’ll need to wrap your text in double quotes. The opposite is also true if you want to put a double quote in your string. Each individual letter, number or symbol can be accessed by using square brackets and an index, in the same way arrays are accessed:

var name = "Sarah";
name[0] // S
name[1] // a
name[2] // r
name[3] // a
name[4] // h

You can also find out the length of a string by using the length property.

var text = "The quick brown fox jumped over the lazy dog.";

text.length // 45

Number

In other programming languages there are separate data types for all kinds of different numbers. But in JavaScript there is just the Number data type that is used to represent any number.

var number1 = 42;
var number2 = 33.3;
var number3 = 3e4; // 1230000

As you can see, either whole numbers such as number1 or decimal numbers like number2 are fine to use. You can also shorten really large numbers by using the exponential syntax like in number3.

Boolean

Booleans are our final primitive JavaScript data type. Booleans can only be one of two values; true or false.

var loggedIn = true;
var paidBills = false;

Booleans are great when used in a JavaScript if statements as you don’t need to check their value with the == or === operator. For example you might write something like this:

var loggedIn = true;
if(loggedIn === true){
  console.log("Welcome to your account.");
} else{
  console.log("Please log in.")
}

But this can be simplified to:

var loggedIn = true;
if(loggedIn){
  console.log("Welcome to your account.");
} else{
  console.log("Please log in.")
}

Because loggedIn is either true or false, this is enough for JavaScript to work out which message to print out.

Complex JavaScript data types

Don’t let the ‘complex’ bit put you off - there’s nothing complicated about these data types. Complex data types are simply made up of different primitive types, presented in a variety of ways. Whereas a primitive type holds one value e.g. 42 or “age” a complex data type will hold multiple values.

Object

With objects, multiple values are held in pairs. These pairs are referred to as key / value pairs. Let’s take a look at an example:

var person = {
  name: "James",
  age: 34,
  email: "james@juniordevelopercentral.com"
}

In the example, I have created an object using curly braces { } which has the keys of name, age and email each with their own corresponding values. Accessing the values that are stored in an object can be done in one of two ways. Either the dot or bracket notation.

var person = {
  name: "James",
  age: 34,
  email: "james@juniordevelopercentral.com"
}

// Dot notation
person.name  // "James"
person.age   // 34
person.email // "james@juniordevelopercentral.com"

// Bracket notation
person["name"]   // "James"
person["age"]      // 34
person['email']  // "james@juniordevelopercentral.com"

Notice how I used single quotes to get the email value using bracket notation. I just did this to show you can use either single or double quotes.

Functions

If you want to repeat a bit of code in different parts of your program, using functions will prevent you from having to copy and paste it over and over. Also, as the code is held in one place, if you want to change it you just update it the once! Functions are considered a data type in JavaScript and this allows them to be assigned to variables and passed around inside your programs. At the end of this article, i’ll show you how to check the data type of a particular variable so you will be able to tell if it is a function.

var addNumbers = function(a,b){
  return a+b;
}

Because the addNumbers variable has had a function assigned to it the data type becomes ‘function’. This doesn’t have a huge impact on the code you write in JavaScript but you can do cool things like this:

var addNumbers = function(a,b){
  return a+b;
}
var sum = addNumbers;

sum(2,2) // Returns 4

By assigning the addNumbers variable to another variable we can use the new variable’s name to access the function that was previously defined. Next, we’ll take a look at the special JavaScript data types available.

Special

There’s an argument to say that these ‘special’ data types aren’t really data types as they don’t contain anything and represent nothing or no data. It’s useful to include them here though as you might want to check if a variable has this type assigned to it in your code.

undefined

This one is simple. If a variable has the undefined data type then it means that the variable hasn’t been assigned a value yet.

var name;
console.log(name); // Displays "undefined"

Technically, undefined is one of JavaScript’s primitive types however, for the purpose of this article it made sense to differentiate it from strings and numbers. Let’s not get hung-up on whether a data type is primitive, complex or anything else shall we?

null

The null ‘data type’ is used to represent nothing, no value, there’s nobody here!

var name = null;
console.log(name); // Displays "null"

In the above example, the name variable is now defined but it points to nothing. It’s not common practice to initialise variables with a null value like above but you might find when working with APIs or JavaScript frameworks that you get a null value back if no data exists for a particular request.

Using the typeof operator

From time to time you’re going to want to check what type of data you are working with. Data retrieved from an API / database and user input are two examples. You can do this with the typeof operator.

var name = "James";
var age = 34;
console.log(typeof name); // Prints 'string'
console.log(typeof age); // Prints 'number' 

If you use the typeof operator on any variable, you can easily determine it’s data type. When might you use this? Imagine if you have a variable called person that has been set as the result of a call to an API. Unfortunately, the API can return a string value or a complex object depending on how it is called. Never fear though - we can write some logic to check this!

// person variable has been set from the API
if(typeof person === 'string'){
  console.log('Hi ' + person); // person variable is just a string so print it as is
} else {
  console.log('Hi ' + person.name); // person variable is an object so access it's 'name' property
}

Things can change

Because JavaScript is weakly typed it doesn’t hit you over the head if you try mess with it’s data types. Example. What do you think the following code will display?

var name = 'James';
name = 23;
console.log(typeof name); // Displays ??

It can either be ‘string’ or ‘number’ and if you run the above code in your browser you would see that the output is actually ‘string’ (name will hold “23” as a string). So you can assign what is essentially a number data type to a string and JavaScript is cool with that. It just means you have to be extra careful when dealing with variables to check that they are the type you are expecting. Another example is adding a number to a string.

var time = "60";
time = time + 40;
console.log(time); // Displays '6040'

The above example looks like you would expect to see 100 right? But JavaScript treats the numeric 40 value as a string and adds it on to the end of the existing 60 string. You can use coercion methods like the Number function or the parseInt function to make sure you get the value you are expecting.

Conclusion

Although JavaScript doesn’t have a huge number of data types it is useful to know the difference between primitives and complex data types. Part of the strength of JavaScript is it’s flexibility in being to assign any value to any variable without first having to have a full awareness of what data is stored. But still, you have to be careful when mixing data types to ensure you don’t get unexpected results in your code.