JS Data Types

In this tutorial, you will learn about the Data Types available in JavaScript.
 

Data Types in JavaScript

In JavaScript, Data can be stored or manipulated within a program. To understand the kind of Data that can undergo such a process, then we must know the basic Data types we have.

We have six basic data types which are split into three main categories and they include:

  1. Primitive or primary Data Types: This specific data type can only hold one value or character at a time. This comprises String, Number, and Boolean.
  2. Composite or reference Data Types: Unlike the Primitive data type, it can hold collections of value and complex entities. This entails Object, Array, and Function (which are all types of objects).
  3. Special Data Types: This consists of Undefined and Null entities.

Since we have understood the three main branches of data type, let's discuss in detail the examples attached to them for more clarification.

 

The String Data Type

This usually represents textual data, in other words, sequences of characters. Strings are created using single or double quotes surrounding one or more characters, as shown below:

Example:

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

Quotes can be added inside the string as long as they don't match the enclosing quotes.

Example:

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

You will learn more about the strings in the JavaScript strings chapter.

 

The Number Data Type

As the name implies, the Number data type is used to represent positive or negative numbers. These numbers can be in decimal places or exponential form. For instance, 1.5e-4 is equivalent to 1.5x10^-4.

Example :

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 is also used to express certain values such as Infinity, -Infinity, and NaN. Infinity is greater than any number and it is mathematically represented by this symbol, ∞. When a non-zero number is divided by 0, the result is Infinity as demonstrated below:

Example:

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

NaN typically means Not-a-Number value. This mostly results during an invalid or an undefined mathematical operation, such as taking the square root of -1 or dividing 0 by 0, etc.

Example :

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

You will learn more about the numbers in the JavaScript numbers chapter.

 

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:

Example:

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

Boolean values can also be used to make a comparison in a program. The following example compares two variables and shows the result in an alert dialog box:

Example:

var a = 2, b = 5, c = 10;
 
alert(b > a) // Output: true
alert(b > c) // Output: false

You will learn more about the comparisons in JavaScript if/else chapter.
 

The Undefined Data Type

The undefined data type can only contain a single value known as a special value undefined. If a variable has been declared but has not been assigned a value, such variable has its value undefined.

Example:

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

 

The Null Data Type

This is another special data type that can have only one value-the null value. A null value simply means that there is no value or void of character. It is not equivalent to an empty string ("") or 0, it is absolutely nothing or emptiness.

A variable must be explicitly emptied of its current contents before recognizing it as a null value.

Example :

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

 

The Object Data Type

The Object is a complex data type that permits you to store collections of data.

An Object is said to be a key-value pair as it contains properties. A property key (name) is always a string, but the value can be any data type, such as Strings,Numbers, or Booleans, or complex data types such as Arrays, Functions, and other objects. You'll learn more about objects in upcoming chapters.

The example below will demonstrate the simplest way to create an object in JavaScript.

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

You will learn more about the objects in the JavaScript objects chapter. 

var emptyObject = {};
var person = {"name": "Rock", "surname": "Star", "age": "36"};
 
// For better reading
var car = {
    "modal": "BMW X6",
    "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 X6",
    color: "blue",
    doors: 5
}

You will learn more about the objects in JavaScript objects chapter.

 

The Array Data Type

An array is a type of object used to store multiple values or elements in a single variable. Each value or element in an array occupies a designated numeric position, known as its index, and it may contain data of any data type numbers such as strings, booleans, functions, objects, and even other arrays. The array index starts from 0, in that the first array element is arr[0], not arr[1] as expected.

The easiest and fastest way to compute an array is by specifying the array elements as a comma-separated list enclosed by square brackets, 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

You will learn more about the arrays in the JavaScript arrays chapter.

 

The Function Data Type

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

Example:

var greeting = function(){ 
    return "Hello World!"; 
}
 
// Check the type of greeting variable
alert(typeof greeting) // Output: function
alert(greeting());     // Output: Hello World!

As a matter of fact, functions can be used at any place any other value can be used. Functions can be stored in variables, objects, and arrays or passed as arguments to other functions. It can also 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

You will learn more about the functions in the JavaScript functions chapter.

 

The type of Operator

The type of operator is used in other to know what type of data a variable or operand entails. This operator can be used with or without parentheses (typeof(x) or typeof x).

The type of operator is particularly useful in certain scenarios in which values of different types need to be processed differently. But extreme caution needs to be put in place to avoid the 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"

From the example above, it is vividly clear that after testing the null value using the type of 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 are written around this behavior, thus fixing it would create a lot more problems, so the idea of fixing this issue was rejected by the committee that designed and maintains JavaScript.