Sign in
Log inSign up
JavaScript Data Types

JavaScript Data Types

Nwocha Chioma's photo
Nwocha Chioma
·Apr 23, 2021·

8 min read

The data types in JavaScript looks simple and useless but having an insight on how they work is essential. So we ask; "what is a data type"?. As its name indicates, a data type represents a type of the data which you can process using your computer program. It can be numeric, alphanumeric, decimal, etc. Data types help to provide a better understanding of the language and its behavior. In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type.

In this article, you will learn about the various data types available in JavaScript with the help of examples.

JavaScript Data Types

There are eight basic data types in JavaScript which can be divided into three main categories:

  • Primitive (primary) Datatypes

  • Non-primitive (reference) Datatypes

  • Special Datatypes

Since JavaScript is a dynamic language, you don’t need to specify the type of the variable. It is dynamically used by the JavaScript Engine.

Primitive (primary) Datatypes

In JavaScript, a primitive data type is data that is not an object and has no methods. Primitive data types can hold only one value at a time. It is pre-defined by JavaScript. The size and type of variable values are specified, and it has no additional methods. JavaScript has three types of primitive data types, based on the type of data we are storing in the variable: String, Number, and Boolean are primitive data types.

1. The String Data Type

The string data type is used to represent textual data (i.e. sequences of characters). Strings are created using single or double quotes surrounding one or more characters, as shown below:

var a = 'Hi there!';  // using single quotes
var b = "Hi there!";  // using double quotes

You can include quotes inside the string as long as they don't match the enclosing quotes.

var a = "Let's have a cup of coffee."; // single quote inside double quotes
var b = 'He said "Hello" and left.';  // double quotes inside single quotes
var c = 'We\'ll never give up.';     // escaping single quote with backslash

2. The Number Data Type

The number data type is used to represent positive or negative numbers with or without decimal place, or numbers written using exponential notation e.g. 1.5e-4 (equivalent to 1.5x10-4).

var a = 25;         // integer
var b = 80.5;       // floating-point number
var c = 4.25e+6;    // exponential notation, same as 4.25e6 or 4250000
var d = 4.25e-6;    // exponential notation, same as 0.00000425

The Number data type also includes some special values which are: Infinity, -Infinity and NaN. Infinity represents the mathematical Infinity , which is greater than any number. Infinity is the result of dividing a nonzero number by 0, as demonstrated below:

alert(16 / 0);  // Output: Infinity
alert(-16 / 0); // Output: -Infinity
alert(16 / -0); // Output: -Infinity

While NaN represents a special Not-a-Number value. It is a result of an invalid or an undefined mathematical operation, like taking the square root of -1 or dividing 0 by 0, etc.

alert("Some text" / 2);       // Output: NaN
alert("Some text" / 2 + 10);  // Output: NaN
alert(Math.sqrt(-1));         // Output: NaN

3. The Boolean Data Type

The Boolean data type can hold only two values: true or false. It is typically used to store values like yes (true) or no (false), on (true) or off (false), etc. as demonstrated below:

var isReading = true;   // yes, I'm reading
var isSleeping = false; // no, I'm not sleeping

Boolean values also come as a result of comparisons in a program. The following example compares two variables and shows the result in an alert dialog box:

var a = 2, b = 5, c = 10;

alert(b > a) // Output: true
alert(b > c) // Output: false

Non-primitive (reference) Datatypes

Non-primitive data types are called reference types because they refer to objects. These data types are not actually defined by the JavaScript but are created by the programmer. They are also called “reference datatypes” since they reference a memory location which stores the data. Object, Array, and Function (which are all types of objects) are non-primitive data types.

1. The Object Data Type

The object is a complex data type that allows you to store collections of data. An object contains properties, defined as a key-value pair. A property key (name) is always a string, but the value can be any data type, like strings, numbers, booleans, or complex data types like arrays, function and other objects. JavaScript objects are written with curly braces {}. Object properties are written as name:value pairs, separated by commas. The following example will show you the simplest way to create an object in JavaScript.

var emptyObject = {};
var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// For better reading
var car = {
    "modal": "BMW X3",
    "color": "white",
    "doors": 5
}

You can omit the quotes around property name if the name is a valid JavaScript name. That means quotes are required around "first-name" but are optional around firstname. So the car object in the above example can also be written as:

var car = {
    modal: "BMW X3",
    color: "white",
    doors: 5
}

2. The Array Data Type

An array is a type of object used for storing multiple values in single variable. Each value (also called an element) in an array has a numeric position, known as its index, and it may contain data of any data type-numbers, strings, booleans, functions, objects, and even other arrays. The array index starts from 0, so that the first array element is arr[0] not arr[1]. JavaScript arrays are written with square brackets. Array items are separated by commas. The simplest way to create an array is as shown in the example below:

var colors = ["Red", "Yellow", "Green", "Orange"];
var cities = ["London", "Paris", "New York"];

alert(colors[0]);   // Output: Red
alert(cities[2]);   // Output: New York

3. The Function Data Type

The function is callable object that executes a block of code. Since functions are objects, so it is possible to assign them to variables, as shown in the example below:

var greeting = function(){ 
    return "Hello World!"; 
}

// Check the type of greeting variable
alert(typeof greeting) // Output: function
alert(greeting());     // Output: Hello World!

In fact, functions can be used at any place any other value can be used. Functions can be stored in variables, objects, and arrays. Functions can be passed as arguments to other functions, and functions can be returned from functions. Consider the following function:

function createGreeting(name){
    return "Hello, " + name;
}
function displayGreeting(greetingFunction, userName){
    return greetingFunction(userName);
}

var result = displayGreeting(createGreeting, "Peter");
alert(result); // Output: Hello, Peter

Special Datatypes

JavaScript special datatypes consist of Undefined and Null are special data types.

1. The Undefined Data Type

The undefined data type can only have one value- the special value undefined. If a variable has been declared, but has not been assigned a value, it has the value undefined.

var a;
var b = "Hello World!"

alert(a) // Output: undefined
alert(b) // Output: Hello World!

Since we have declared the variable a but without assigning any value, it is an undefined variable. Normally, we use undefined for checks like seeing if a variable has a value assigned.

2. The Null Data Type

This is another special data type that can have only one value-the null value. A null value means that there is no value. It is not equivalent to an empty string ("") or 0, it is simply nothing. A variable can be explicitly emptied of its current contents by assigning it the null value.

var a = null;
alert(a); // Output: null

var b = "Hello World!"
alert(b); // Output: Hello World!

b = null;
alert(b) // Output: null

The typeof Operator

The typeof operator can be used to find out what type of data a variable or operand contains. It can be used with or without parentheses (typeof(x) or typeof x). The typeof operator is particularly useful in the situations when you need to process the values of different types differently, but you need to be very careful, because it may produce unexpected result in some cases, as demonstrated in the following example:

// Numbers
typeof 15;  // Returns: "number"
typeof 42.7;  // Returns: "number"
typeof 2.5e-4;  // Returns: "number"
typeof Infinity;  // Returns: "number"
typeof NaN;  // Returns: "number". Despite being "Not-A-Number"

// Strings
typeof '';  // Returns: "string"
typeof 'hello';  // Returns: "string"
typeof '12';  // Returns: "string". Number within quotes is typeof string

// Booleans
typeof true;  // Returns: "boolean"
typeof false;  // Returns: "boolean"

// Undefined
typeof undefined;  // Returns: "undefined"
typeof undeclaredVariable; // Returns: "undefined"

// Null
typeof Null;  // Returns: "object"

// Objects
typeof {name: "John", age: 18};  // Returns: "object"

// Arrays
typeof [1, 2, 4];  // Returns: "object"

// Functions
typeof function(){};  // Returns: "function"

As you can clearly see in the above example when we test the null value using the typeof operator (line no-22), it returned "object" instead of "null". This is a long-standing bug in JavaScript, but since lots of codes on the web written around this behavior, and thus fixing it would create a lot more problem, so idea of fixing this issue was rejected by the committee that design and maintains JavaScript.

Summary

With this, we come to the end of our article on JavaScript Datatypes. In the above article, we took a brief look at what is JavaScript data types, the three main categories JavaScript data types : primitive ,non-primitive and special data types, typeOf() Operator. After learning about data types, you have entered into the world of JavaScript. You need to understand the code really well before moving forward.