JS Data Types

Data Types in JavaScript

Data types essentially define what kinds of data can be stored and manipulated within a program.

JavaScript has six basic data types, which fall into three main categories: primitive, composite, and special data types. String, Number, and Boolean belong to the primitive category. Object, Array, and Function (all types of objects) fall under composite data types. Undefined and Null are special data types.

Primitive data types can store only single values, while composite data types can hold collections of values and more complex entities. Let's delve into each of them.

The String Data Type

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

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

You can include quotation marks within a string as long as they are different from the quotes used to enclose the string.

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'll discover more about strings in the JavaScript strings chapter.


The Number Data Type

The number data type is used to represent positive or negative numbers with or without a decimal place, or numbers written using exponential notation, such as 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 encompasses some special values: Infinity, -Infinity, and NaN. Infinity represents mathematical infinity , which is greater than any number. Infinity is the result of dividing a nonzero number by 0, as illustrated below:

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

Meanwhile, NaN represents a special Not-a-Number value. It occurs as a result of an invalid or undefined mathematical operation, such as taking the square root of -1 or dividing 0 by 0, among others.

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

You'll explore numbers further in the JavaScript numbers chapter.


The Boolean Data Type

The Boolean data type can only hold two values: true or false. It's commonly used to represent yes (true) or no (false), on (true) or off (false), and similar scenarios, as shown below:

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

Boolean values can also result from comparisons in a program. The following example compares two variables and displays the result in an alert dialog box:

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

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

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


The Undefined Data Type

The undefined data type has only one value: undefined. If a variable is declared but not assigned a value, it's considered undefined.

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 has only one value: null. The null value indicates the absence of any value. It's distinct from an empty string ("") or 0; it represents nothingness.

A variable can be explicitly cleared 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 Object Data Type

The object is a complex data type used for storing collections of data.

An object consists of properties, which are defined as key-value pairs. The property key (name) is always a string, while the value can be any data type, such as strings, numbers, booleans, or even complex data types like arrays, functions, and other objects. You'll explore objects further in upcoming chapters.

The following example illustrates 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
}

If the property name is a valid JavaScript identifier, you can omit the quotes around it. This means quotes are necessary for "first-name", but optional for firstname. Therefore, the car object in the previous example can also be expressed as:

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

You'll learn more about objects in the JavaScript objects chapter.


The Array Data Type

An array is a type of object used to store multiple values in a single variable. Each value, also called an element, in an array has a numeric position known as its index. It can contain data of any data type: numbers, strings, booleans, functions, objects, and even other arrays. The array index starts from 0, so the first array element is arr[0], not arr[1].

The simplest way to create an array is by specifying the array elements as a comma-separated list enclosed in square brackets, as demonstrated 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 JavaScript arrays chapter.


The Function Data Type

A function is a callable object that executes a block of code. Since functions are objects, it's possible to assign them to variables, as illustrated 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 wherever any other value can be used. They can be stored in variables, objects, and arrays. Functions can also be passed as arguments to other functions, and they 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

You'll learn more about functions in the JavaScript functions chapter.


The typeof Operator

The typeof operator can determine the type of data contained in a variable or operand. It can be used with or without parentheses (typeof(x) or typeof x).

The typeof operator is particularly useful in situations where you need to handle values of different types differently. However, you must be cautious because it may produce unexpected results in some cases, as shown 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 evident in the example above, when we test the null value using the typeof operator (line no-22), it returns "object" instead of "null".

This discrepancy in JavaScript has been a longstanding issue. However, because many existing codes rely on this behavior, fixing it would create more problems. As a result, the proposal to fix this issue was rejected by the committee responsible for designing and maintaining JavaScript.