Data Types In JavaScript

JavaScript has a range of data types that we can use in our programs, and we'll break down the most essential ones in this lesson.

We will cover:

What are data types?

Data types specify the kinds of data that can be stored and manipulated in a program.

In JavaScript, data types can be categorised into the following groups:

  • Primitive types
  • Non-primitive types

In the current specification there are seven primitive types and one non-primitive type.

Primitive types

JavaScript has the following primitive types:

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • BigInt
  • Symbol

Non-primitive types

As mentioned, there is just one non-primitive type available:

  • Objects

Let's explore each of these types one by one, and how they can help you develop your own programs in JavaScript.

String

A String is a sequence of characters that represent a text value.

In JavaScript strings are surrounded by quotation marks, for example:

const name = 'Gandalf';

Note that above we're using single quotes '' to declare the string. We can also use double quotes:

const name = 'Gandalf';
const location = "Middle Earth";

In addition, we can even use backticks:

const name = 'Gandalf';
const location = "Middle Earth";
const rank = `Grey`;

The location of the backtick key on your keyboard can vary depending on the operating system you're using.

Note that if you're using a formatter, such as Prettier, double quotes "" may be converted to single quotes '' on save, depending on your configuration settings.

Number

In JavaScript the Number type is used to represent floating-point numbers.

For example, 37 and 3.7 are both treated as floating-point values, not integers.

In computer science, integers and floats are two different kinds of numerical data. An integer (often referred to as int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed, for example when dealing with monetary values.

Different programming languages can represent numbers differently, but for now just know that you can use Number for whole numbers and decimal numbers.

You can declare numbers like so:

const sum = 0;
const price = 2.99;

Boolean

A Boolean type represents logical entities and can only have one of two values: true or false. For example:

const isMoving = true;
const isLoggedIn = false;

Booleans are most often used to execute code conditionally based on a particular value being true or false.

Undefined

The undefined data type is used to represent a value that is not yet assigned.

In other words, if a variable is declared but is not yet given a value, then the value of that variable will be undefined.

In the following example the variable total is declared, but a value has not been assigned to it:

let total;
console.log(total);

If you try to log this value to the console it will print undefined.

In addition, you can also set the value of undefined explicitly:

const response = undefined; 

Notice that you do not need to use quotes '' around undefined - instead you are explicitly referring to the undefined type itself.

Null

null is a special value in JavaScript that specifically represents no value or an unknown value:

const tax = null;

So when should you use null or undefined? Preferably null should be used to represent a null value and undefined should be used to represent a value that is yet to be defined.

If you want to explicitly assign a value of 'not known', use null instead of undefined.

BigInt

BigInt is a more advanced data type and we won't be exploring examples of it in this foundational lesson.

It is a relatively recent addition to the JavaScript language, and it is used to denote an integer value that is too large for the regular Number type to hold.

Indeed most programming languages have more than one way to store a number, and this touches on wider concepts in computer science. For now we'll focus on the Number type.

Symbol

The Symbol data type was introduced in 2015 and denotes a value that is unique and immutable i.e. it cannot be changed.

As a beginner you don't need to worry about BigInt or Symbol types for now.

Primitive vs non-primitive

A primitive value, for example a string or a number, is written as an actual value:

const name = 'Gandalf';

const sum = 0;

On the other hand, a non-primitive type is a collection of values...

Objects

In JavaScript an object is a complex data type containing properties defined as key-value pairs.

To define an object we start with a variable declaration, followed by the object literal syntax using curly braces {}:

const character = {
	'firstName': 'Frodo',
	'lastName': 'Baggins',
	'age': 50
}

Keys are declared on the left of the colon : and values are assigned on the right.

A key can only be of type String or Symbol. A value can be any data type that you'd like.

In addition, if the key is a valid name in JavaScript (i.e. it doesn't contain any hyphens) you can remove the quotation marks:

const character = {
	firstName: 'Frodo',
	lastName: 'Baggins',
	age: 50,
};

A formatting tool like Prettier can format this for you automatically on save.

Accessing object properties

To access the property of an object we can use 'dot notation'. For example, you can access the character's first name and log it to the console like so:

console.log(character.firstName); // Frodo

If you run the above code you should see the string 'Frodo' outputted to the console.

We can also use square bracket [] notation to access object values, providing the keys as strings:

console.log(character['firstName']); // Frodo

This approach is required when the object keys use kebab case (words separated with hyphens):

const character = {
	'first-name': 'Frodo',
	'last-name': 'Baggins',
	age: 50,
};

console.log(character['first-name']); // Frodo

It's best to avoid kebab case where possible, but you're likely to encounter it out in the wild so it's worth being aware of.

Arrays

The object literal syntax (with curly braces {}) is one way to store a collection of data.

There is another method for storing data that you should be aware of as a beginner, known as the Array type.

Arrays are written using square brackets [], and the items within an array are separated with commas.

We can define an array of numbers like so:

const evenNumbers = [2, 4, 6, 8, 10];

Accessing array values

To access a value in an array we use the position of the item, known as the index.

In JavaScript arrays are zero-indexed, meaning that the index starts at 0.

Zero-indexing is very common in programming. Don't worry if it seems strange at first, as it will soon become second nature.

We provide the index inside of square brackets like so:

const evenNumbers = [2, 4, 6, 8, 10];

console.log(evenNumbers[0]); // 2

The above code will output the number 2 to the terminal, as it is in position 0 and is the first element in the array.

If you instead provide an index of 1 you should see the number 4 printed in the terminal:

console.log(evenNumbers[1]); // 4

Dynamic vs static typing

JavaScript is what's known as a dynamic language with dynamic types. Variables are not linked to any specific data type, and the type of a variable can be re-assigned at any point.

This is different to statically typed programming languages, where the data types of values are explicitly declared.

You don't need to worry too much about this as a beginner, however the dynamic nature of JavaScript will make a difference to how you write your code.

In JavaScript you don't have to specify the data type of a variable when you declare it. In addition the data types are automatically converted as needed during execution of the code.

Let's explore this with an example. We'll declare a new variable a and assign a number as a value:

let a = 2;

On the next line we can change the value to a string:

let a = 2;
a = 'Gandalf';

Indeed you can assign any value you'd like:

let a = 2;
a = 'Gandalf';
a = false;

The value of the variable will be whatever value was assigned last. If you log a to the console you should see a value of false:

let a = 2;
a = 'Gandalf';
a = false;

console.log(a); // false

This confirms that the value of a can be reassigned successfully.

As a dynamic language, JavaScript is perfectly happy with this and does not throw an error. A statically typed language, on the other hand, would not allow it.

Summary

In this lesson you've learned the essential data types in JavaScript, including primitive and non-primitive types, the differences between them, and how to work with each individual data type.

In addition, you also learned that JavaScript is what's known as a dynamic programming language, as opposed to a statically typed language.