Data types in JavaScript Explained

  • 10 min read
  • October 29, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

Values in JavaScript each have a data type.

JavaScript has multiple different data types, and each type has a different set of properties and methods. These properties and methods are specific to the type of data being worked with.

These data types also interact with each other when used in expressions, and the result of these interactions is also type-dependent. For example, adding a String to a Number results in the two values being concatenated as though they were both strings:

const str = 'Im a string';
const num = 3;
console.log(num + str);
// Expected output: 3Im a string

In the example above, const str is of type String, and const num is of type Number. When adding these two consts, the result is a String: ‘3Im a string’.

It is possible to get a value’s data type using the typeof operator. This operator is used in many of the examples below to help in identifying the type of data being worked with.

JavaScript currently has nine data types – seven primitive data types, and two structural data types (Objects and Functions).

 

Primitive data types

The seven primitive data types are: String, Number, BigInt, Boolean, undefined, null, and Symbol.

 

1. String

The String type represents textual data.

A String consists of a collection of characters. Each character has its own index in the string (starting from zero), and the total number of characters in the String is known as the String’s length. Index and length are properties of the String data type.

JavaScript Strings are immutable, meaning that once they have been created, they cannot be changed.

String example

The following example demonstrates how to create a String in JavaScript:

const str = 'I am a string';
console.log(typeof str);
// Expected output: string

In the example above, const str stores the text ‘I am a string’.

 

2. Number

The Number type represents numbers ranging from a minimum value of -(253 – 1) up to a maximum value of (253 – 1). The Number type includes Integers (whole numbers and their opposites) like 12 and -5, floating point numbers (rational numbers) like 1.56 and -4.53; and three symbolic values: Infinity , -Infinity and NaN (not a number).

Number example

The example below shows how to create a Number in JavaScript:

const num = 3;
console.log(typeof num);
// Expected output: number

In the example above, const num stores the value of a number: 3.

You can use the Number.isInteger() method to check whether a given value is an integer, as seen below:

console.log(Number.isInteger(num));
// Expected output: true

In the example above, the Number.isInteger() method is applied to const num. Since num is an integer, this method returns the Boolean type true (more on this below).

To convert a String into a Number, use the parseInt() method:

const numStr = '-16';
const num = parseInt(numStr, 10);
console.log(num);
// Expected output: -16

In the example above, const numStr stores a string representing the number -16. Using the parseInt() method, the String value “-16” is converted to a Number -16 and stored in const num.

 

3. BigInt

In rare cases, the range of possible values that data type Number covers is not large enough to represent the desired data. BigInts allow us to safely handle large integers, both positive and negative, that fall outside the range of the Number data type.

To create a BigInt, simply append an n to the end of an integer

const bignum = 17573547548754873982135326536n;
console.log(typeof bignum);
// Expected output: bigint

Although Numbers and BigInts are closely related, they do not interact very well.

const num = 17573547548754873982135326536;
const bignum = 17573547548754873982135326536n;
const huge = num * bignum;
// Expected output: 
// Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

In the example above const num is a Number and const bignum is a BigInt. When trying to multiply the two, we get a TypeError.

Furthermore, if you will check the numbers in the example, they are the same, except for the ‘n’ at the end of const bignum. But trying to equate the two results to false , even though we are not using the strict equality operator:

console.log(num == bignum);
// Expected output: false

The example above demonstrates that when comparing two equivalent numbers, where one is of type Number and the other is of type BigInt, the equality operator returns false despite the two numbers being identical. We’ll cover the Boolean data type in the next section.

 

4. Boolean

Boolean is a logical data type that has only two values – true and false.

Booleans play a large role in conditional statements, such as when using an if statement (e.g. if something is true, execute this code…). They are also used for other types of verification, as we saw above with the method Number.isInteger(). Let’s take a look at this using our last example from the BigInt section:

console.log(num == bignum);
// Expected output: false

In the above example, since const num is not equal to const bignum, the expression returns false.

 

5. undefined

The undefined data type refers to a variable which has been declared but has not yet been assigned a value.

let x;
console.log('variable x is ', x);
//Expected output: variable x is undefined

In the above example, let x is declared but not assigned any value. Therefore, its type is undefined.

Note: the code above uses the keyword let to define a variable, and not the keyword const. This is because const variables must always be declared with a value.

If the variable referenced has not yet been declared, it is instead “not defined”. Let’s explore this with an example:

console.log('variable y is ', y);
// Expected output:
// Uncaught ReferenceError: y is not defined

Note: a variable being not defined is very different from variables that are undefined. It suggests that the specified variable does not exist in the program (has not been defined), whereas undefined refers to a variable that has been declared but has not yet been assigned a value.

It is possible to explicitly assign undefined to a variable, as we see below:

let u = undefined;

 

6. null

Null is a special primitive data type. It has only one value – null. This represents the intentional absence of value. It may be used to “empty” or “clear” a variable of its former value(s), or to declare that the value of something is not yet known (e.g. let address = null).

Syntax

let n = null;

Note: applying the typeof operator to null returns ‘object’, unlike all other primitive data types.

console.log(typeof n);
// Expected output: object

 

7. Symbol

Symbols are used to create unique IDs for Objects. Understanding the power of Symbols requires some knowledge of how Objects work in JavaScript. In order to keep this article focused, we’ll skip ahead to discuss Objects.

 

Structural types

The structural data types include Objects, and Functions (which are a special kind of Object).

Object

In JavaScript, Objects are regarded as data structures because – unlike the other seven primitive data types – they are able to store multiple values with a mixture of data types. That makes Objects unique and extremely valuable, and has resulted in Objects becoming one of the fundamental elements of modern JavaScript. The following example code demonstrates how to create an Object:

const user = {
    name: 'Alex',
    age: 37,
    admin: false,
    login: function () {
        return 'loggedin'
    },
    history: null,
    favColor: undefined
};

In the above example const user is an Object which stores multiple values of different data types.

An Object’s data is stored in key: value pairs called properties. These properties can also contain methods for functions.

Using a for…in statement enables us to iterate over an Object’s properties one at a time, as we see below:

for (let property in user) {
    console.log(property + ' is of type: ' + typeof user[property]);
}
// Expected output:
// name is of type: string
// age is of type: number
// admin is of type: boolean
// login is of type: function
// history is of type: object
// favColor is of type: undefined

The example above uses the for…in statement to iterate over the user object, printing the type of each property to the console.

Objects are extremely flexible, and useful in a large number of scenarios. To learn more about objects, follow this link.

Note: JavaScript Arrays are also objects.

 

Arrays are list-like data structures. While they have the capability to store multiple data types just like objects, it is more common to find Arrays that contain only a single type of data at a time (e.g. a list of Numbers, a list of Strings, etc.).

const myLuckyNums = [6, 36, 43, 98];

In the example above, const myLuckyNums is an Array storing my lucky numbers.

Arrays use square brackets, not curly ones like objects. Arrays have implicit “keys” that are not defined in the code itself, but rather are integers representing the index of each value within the array. Array indices in JavaScript are zero-based. The following example shows how to refer to an individual element of an array using an index:

console.log(myLuckyNums[2]);
// Expected output: 43

In the example above, the third number (which, due to starting at 0, is located at index 2) is retrieved from the array.

 

Function

JavaScript functions, like Arrays and others, are also objects. These objects, however, have a unique quality – they can be invoked, or called into action on demand. That capability makes them an essential component of JavaScript (or any other programming language for that matter). Functions spark life in the code, making it dynamic.

A function is a block of code designed to execute a task. This task could be performing a calculation, printing something to the console, downloading a file, getting an input’s value, or many more. Functions are able to execute an endless variety of tasks, limited only by the imagination of the programmer.

let a = undefined;

function mult(num1, num2) {
    return a = num1 * num2;
}

mult(7, 3);
console.log(a);
// Expected output: 21

In the example above, function mult() is used to change the value of the variable a (defined by let a). This function receives two parameters, num1 and num2, with a name indicating that these parameters should be numbers. The function returns an assignment to variable a, storing the result of num1 multiplied by num2. It is important to note that, even if no return statement is provided, every function returns something.

The function is invoked by typing its name followed by parentheses. In the code above, this consists of appending parentheses to the name of the function mult. Parameters to the function are provided as a comma-separated list in the parentheses following the function name. Invoking a function without providing arguments for the required parameters will lead to an undesirable result (unless the parameters have been marked as optional). In the above case, failing to provide arguments to the mult function will result in the value NaN (not a number). This happens because the function tries to multiply undefined by undefined, as no value was assigned to either of the parameters.

To learn more about functions, follow this link.

 

Related Articles

JavaScript – Objects Explained

JavaScript – How to Use Asynchronous Functions

JavaScript – How to Use The Array forEach() Method

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each