Data Types in JavaScript

A data type in JavaScript specifies the specific type of value that a variable can store. In other words, a data type is simply a “kind” of value (i.e. data) stored in a variable.

Internally, a variable represents a memory location where data stores. Data is information that we store in computer programs. For example, name, age, the color of your hair, how many siblings you have, where you live, whether you’re male or female, numbers, etc. All these things are data.

The data type in JavaScript determines how much memory will allocate for the data stored in a variable.

In the most programming languages, we require to specify the type of data a variable will store. But, JavaScript does not impose any restriction in this context because variables in JavaScript have dynamic data types. It means that they can hold different data types at different times. Let’s understand it clearly with the help of examples.

What is Dynamic Data Types in JavaScript?


JavaScript is a dynamic and loosely typed, or duck typed language. It means that we do not need to specify the type of variable because JavaScript engine dynamically determines the data type of a variable based on its values.

In other words, the value we assign to the variable determines its data type. JavaScript automatically handles different types of values and automatically converts values from one type to another.

That is, it does not prohibit a variable from changing the type of value while programming.

JavaScript simply allows for creating a generic variable using the keyword var. The actual data type used depends on the initial value that we will assign to the variable.

Consider the following examples:

var FirstName = “Shubh” // Holding string.
var AccountNumber = 123499 // Holding number.

As you observe in the above code, the variable var can hold any type of values, such as strings, numbers, etc. Hence, JavaScript is considered as a “loosely typed language”. We can put any data to a generic variable.

As a result, we can use the same variable to hold a variety of different values, such as integer, float, string, boolean value, etc. For example:

var my_var = "Hi Friends!"; // holding string.
  my_var = 25; // same variable holding numeric value.
  my_var = true; // same variable holding boolean value.

Other languages (Java, C, C++, etc.) will not allow to create a generic variable of an unspecified type. Therefore, such languages are known as “strongly typed languages”.

Types of Data types in JavaScript


Like any other programming language, JavaScript language allows us to work with the seven data types. A list of all data types are as follows:

  1. Numbers
  2. Strings
  3. Booleans
  4. Null
  5. Undefined
  6. Objects
  7. Arrays

The first three data types are primitive data types in JavaScript because they store only single values. The next two are called trivial data types and the last two composite or reference data types.

JavaScript Data Types

Let’s understand the first three primitive data types in JavaScript through various example programs.

JavaScript Primitive Data Types


Primitive data types are the set of all basic building blocks for which data represents. They are manipulated directly by their values. In JavaScript, there are three types of primitive data types.

  • Numbers
  • Strings
  • Boolean

Primitive data types in JavaScript can only store a single value within the associated variable. It cannot store additional properties or methods along with the data because they are not objects. All primitive data types, except the undefined and null, also have a wrapper object in JavaScript.

By default, primitive data types are immutable in JavaScript, meaning that once a primitive value is created, the value itself cannot be altered. Any operations that attempt to modify the value actually create a new value.

For example, adding to a string results in a new string, because the original string cannot be changed. However, a newly created value can be initialized to another variable. Let’s understand all three primitive data types one by one.


1. Numbers:

Numbers in JavaScript are used to represent both integers and floating-point numbers. For example, we can represent your age as a number. Numbers look like this: 1, 23, 10.50, 23.8990, etc.

Like other languages like C, C++, Java, JavaScript language do not provide special or separate data types for integers and floating-point numbers. It does not make a difference between integer values and floating-point values. It considers all numbers as floating-point values.

JavaScript language represents numbers by using the 64-bit floating-point format defined by the IEEE 754 standard. Let’s consider a very simple example program where we will assign some numeric values to variables.

Example 1:

<script>
      var x1 = 5;
      var x2 = 10;
      var x3 = 15;
      var x4 = 20.25;
     document.write(x1 + "<br>"); // It simply prints or display on the current webpage.
     document.write(x2 + "<br>");
     document.write(x3 + "<br>");
     document.write(x4);
</script>
Output:
           5
           10
           15
           20.25

2. Strings:

A string is another type of data that comprises a sequence of alphanumeric characters. It is basically a line of text surrounded by quotation marks.

For example, “Hello World!”, “666-2829”, “KA23VABSN”, etc. Enclosing a group of characters, or a line of text in a single or double quote shows it is a string. For example:

var name = "Shubh"; // String.
alert( name ); // This will alert "Shubh".

When wrapping a number in quotes and assigning it to a variable, JavaScript will consider the number as a string. For example:

var num = "5";
alert( num + num ); // This will alert "55".

We know that plus sign (+) is used to add numbers. When we will use plus sign (+) with strings, the plus sign concatenates strings together like this:

var firstName = "Shubh";
var lastName = "Deep"
document.write(firstName + lastName); // It will print ShubhDeep.

If we add a number and string, JavaScript will assume the number as a string. For example:

1. var x = "5";
    var num = "five";
    document.write(x + num); // It will print 5five.

2. var num = 25 + 30 + "five";
    document.write(num); // It will print 55five because JavaScript will treat 25 and 30 as numbers. That’s why it is adding.

3. var num = "five" + 20;
    document.write(num); // Print five20.

4. var num = "five" + 20 + 30;
    document.write(num); // Print five2030 because the first operand is a string.
   // Therefore, JavaScript interpreter will consider all operands as strings.

3. Boolean:

We can also assign a variable with boolean values (true or false). JavaScript provides built keywords true and false to define boolean values, so quotation marks are unnecessary.

For example:

vvar booleanValue = true; // The variable booleanValue is now true.

We often use boolean values in conditional testing. For example, consider the following statements:

If (num > 18) {
   // do something
}

In this example, we have used a boolean expression (num > 18) within the if statement to check whether the code within braces will execute.

If the variable num is greater than 18, the Boolean expression evaluates to true; otherwise, it evaluates to be false.

Trivial Data Types


1. Null:

Null is another special data type in JavaScript. It means nothing (i.e. an empty value). It represents and evaluates to false. Assigning a value null to a variable means it contains nothing. For example:

var value = null;
alert(value); // This will open a dialog containing "null".

Don’t confuse between null and empty value. Empty value differs from null, which is just plain nothing. For example, declaring a variable and assigning its value to an empty string looks as:

var myVariable = ' ';

The variable myVariable is empty, but not null.


2. Undefined:

Undefined is the declaration of a variable without a value. The type is also undefined. For example:

var num; // Value is undefined, type is undefined
document.write(num); // It will print undefined.

Here, there are two lines of code. The first line declares a variable named num. The declaration of variable tells the JavaScript engine to allot a memory space that we can use to store data. As we are not assigning any data to variable num, the subsequent line will return undefined.

Undefined is different from null, but both null and undefined evaluate the same way.

Non-primitive Data Types (Reference Data Types) in JavaScript


There are three non-primitive data types in JavaScript. Non-primitive data types are also called composite or reference data types in JavaScript. They are as follows:

  • Objects
  • Arrays
  • Functions

These non-primitive data types are manipulated by reference. Non-primitive data types in JavaScript are capable of storing multiple values under a single variable. It also allows us to store different properties and methods along with the data in a variable. Non-primitive data types are mutable in JavaScript, meaning that we can modify them still after the creation.

Let’s understand all three non-primitive data types in JavaScript with example programs one by one.


1. Objects:

Objects in JavaScript are a set of properties, each of which can contain a value. We write these properties as name: value pairs (or key: value pairs), separated by commas in JavaScript.

Each value stored in the properties can have a value, another object, or even a function. We can also define our own objects or can use several built-in objects.

Javascript objects are created with curly braces. Let’s understand them with help of some examples.

a) var myObject = { }; // an empty object.

b) An object with several properties:
    var person = {
                     firstName: "Ivaan",
                     lastName : "Sagar",
                     age: 04,
                     eyeColor: "blue",
                     hairColor: "black"
                  };

The preceding code example creates an object called person, that has five properties: firstName, lastName, age, eyeColor, and hairColor. The values contained in each property are Ivaan, Sagar, 04, blue, and black respectively.

The .operator is used to access the property of an object. For example, we can access the lastName property of the person object like this:

document.write(person.lastName); // It will print Sagar.

The complete script code structure is as follows:

Example 2:

<script>
var person = {
               firstName: "Ivaan",
               lastName: "Sagar",
               age: 04,
               eyeColor: "blue",
               hairColor: "black"
    };
  document.write("Full name : " +person.firstName + " " +person.lastName+ "<br>");
  document.write("Age: " +person.age +"<br>");
  document.write("Eye color: " +person.eyeColor+ "<br>");
  document.write("Hair color: " +person.hairColor)
</script>
Output:
           Full name: Ivaan Sagar
           Age: 4
           Eye color: blue
           Hair color: black

We will learn more about objects later in the further tutorials.


2. Arrays:

An array is a group of multiple values that we can assign into a single variable. The values in an array are unsigned integers called array index. The array index starts at zero.

Therefore, the index number 0 contains the first member, the index 1 contains the second member, index 2 has the third member, and so on. We write an array within square brackets ([ ]) in JavaScript. Items or elements in an array must separate by commas.

Let’s understand it with the help of an example program.

Example 3:

<script>
 var num = [20, 40, 50];
 document.write(nums[0], "<br>");
 document.write(nums[1], "<br>");
 document.write(nums[2]);
</script>
Output:
           20
           40
           50

We will learn more about arrays later in the further tutorial.


3. Functions:

A function is a block of JavaScript code that is written once and execute when “someone” calls it. JavaScript provides some pre-defined functions and we can also define our own function called user-defined functions.

The definition of a function looks like this:

function sum(x, y) {
     return x + y;
}

We will learn more about functions data type in the function chapter of JavaScript.

Typeof Operator in JavaScript


The typeof operator in JavaScript is used to find the type of a JavaScript variable. It returns the type of a variable or an expression.

Let’s understand it with the help of an example program.

Example 4:

<script>
  var x = 20;
  var name = "Ivaan";
  document.write(typeof 20+ "<br>");
  document.write(typeof "name");
</script>
Output:
          number
          string

Memory Allocation for Primitive Values


JavaScript variables may contain two different types of values: primitive values and reference values. Primitive values are those data that are stored in a stack memory location. These values are directly stored in a single memory location that variable can access them.

On the other hand, reference values are objects that are stored on the heap, meaning that the value stored in a variable is actually an address that points to another memory location where the object is stored.

When we assign a value to a variable, the interpreter determines whether it is primitive or non-primitive (i.e. reference) value. If it is primitive type value, the interpreter stores it in a small memory area known as stack because values of primitive data types takes up a fixed amount of space in the memory. However, in many languages, such as Java, strings are considered a reference data type, not a primitive data type, because a string can vary in length.

Look at the below figure how JavaScript allocates memory location for different data types.

How JavaScript allocates memory location for different data types

Memory Allocation for Non-primitive (Reference) Values


When we assign a reference value, such as an object, array, or function, to a variable, the interpreter typically stores this data in the heap. The heap is dynamic memory allocation, which is used for storing complex data structure whose size might change during the execution of program or is not known at compile-time.

Reference values cannot be stored on the stack, because they have no fixed sizes. They can grow in size. A memory address does have the fixed size, so it can easily place on the stack memory. The value placed in the stack space is actually an address of the location in the heap where the object is stored.

In other words, the variable that you use to store an object does not actually contain the object itself, but rather a reference (a memory address) to the location in the heap where the object data is stored. This reference points to the object’s data, allowing the variable to access and manipulate the object indirectly.

When variable lookup occurs, the memory address is first read and then the value on the heap is recovered using that address. When we access a variable that holds a reference value, the interpreter first reads the memory address and then retrieves the actual data stored on the heap, which we use as needed in the JavaScript code. Look at the above figure.

The above figure show several values of primitive data types stored on the stack. Each variable of a primitive data type generally occupies a specific amount of memory and is accessed directly.

When there is a memory address on the stack, it acts a pointer that points the object located on the heap memory. The heap is not accessed sequentially, because object may take different amounts of memory space. They may expand or shrink dynamically.