Data Types Supported by JavaScript | The Building Blocks of JavaScript

A Guide to JavaScript Data Types: Essential Knowledge for Developers to Harness the Power of JavaScript

Karthik Shetty
12 min readJul 6, 2023

JavaScript supports several data types which help us manage data effectively. These are categorized into 2 types:

  1. Primitive data type
  2. Non-primitive data type

Primitive data types

All primitive data types in JavaScript are ‘Call by Value’. This means that when you copy a primitive value from one variable to another, JavaScript creates a new copy of the value rather than just referencing the original. So, the new variable will have the same value, but they are independent of each other.

Primitive data types are also known as in-built data types and all have their corresponding object wrapper types except null and undefined ones. Below you can see them along with the typeof return values:

Non-primitive data types

Non-primitive data types are driven from primitive data types of the JavaScript language, also known as reference types.

Non-primitive data types (objects, arrays, functions, etc.) are stored in memory and are referenced by variables. This means that when you assign an object or an array to a variable, you are assigning a reference to the memory location where the data is stored, not the data itself.

In JavaScript, non-primitive data types include objects, arrays, functions, and more.

let obj1 = { name: "Alice" };
let obj2 = obj1;

obj2.name = "Bob";

console.log(obj1.name); // Outputs: "Bob"

In this example, obj1 and obj2 reference the same memory location. Changing a property of obj2 also changes the property in obj1, because they point to the same object.

Now we will see one by one.

Primitive data types in JavaScript.

Number

As the name suggests In Number data type we can store numbers. Unlike other programming languages, JavaScript will store all types of numeric values integers and floating-point numbers. It allows you to perform various mathematical operations and manipulate numeric data in your JavaScript programs.

Now we will see the Number data type in detail.

Integer and floating-point Numbers in JavaScript Number data type:

As I mentioned above JavaScript does not differentiate between integer and floating-point numbers. All numeric values are stored as floating-point numbers internally. For example, both 42 and 3.14 are considered Number values.

JavaScript Number data type Arithmetic operations:

The Number data type supports arithmetic operations such as addition (+), subtraction (-), multiplication (*), and division (/). You can use these operators to perform mathematical calculations with Number values.

JavaScript Number data type Numeric Literals:

We can define number values directly in our code using numeric literals. Numeric literals can be written in decimal (e.g., 255 ), hexadecimal (0xff), binary (0b11111111) formats, and so on.

255; // two-hundred and fifty-five
255.0; // same number
255 === 255.0; // true
255 === 0xff; // true (hexadecimal notation)
255 === 0b11111111; // true (binary notation)

JavaScript Number data type Special Numeric Values:

JavaScript provides special numeric values that have specific meanings:

  • NaN (Not-a-Number): Represents an invalid or unrepresentable value resulting from an arithmetic operation. For example, 0/0 or Math.sqrt(-1) produces NaN.
  • Infinity and -Infinity: Represent positive and negative infinity, respectively. They are the result of dividing a non-zero number by zero or exceeding the upper or lower bounds of representable numbers.

JavaScript Number data type Numeric methods:

The Number data type has built-in methods that allow you to perform operations or retrieve information about numeric values. Some commonly used methods include:

  • toFixed(): Converts a number to a string representation with a fixed number of decimal places.
  • toPrecision(): Converts a number to a string representation with a specified precision.
  • toString(): Converts a number to a string representation.
  • parseInt(): Parses a string and returns an integer value.
  • parseFloat(): Parses a string and returns a floating-point value.

Number() method:

When we write numbers in string format inside Number() method it will convert it into a number. If we try to convert characters then it will give NaN value. If we pass undefined it will give NaN value. If we pass True or False it will give 1 or 0. If we pass new Date() it will give the current date in the number format.

Number("123"); // returns the number 123
Number("123") === 123; // true

Number("unicorn"); // NaN
Number(undefined); // NaN

Number(true); // 1
Number(false); // 0

Number(new Date()); // 1687864762905

String

In JavaScript, the String data type represents sequences of characters and is used to store and manipulate textual data. Strings can contain letters, numbers, symbols, and special characters.

String value will be enclosed in either single quotes (') or double quotes ("). For example, 'Hello', "JavaScript", or "123".

JavaScript String type will allow us to perform different actions of string value like Concatenation, Check string Length, and so on.

String Concatenation:

JavaScript allows you to concatenate strings using the + operator. When you concatenate two strings, they are combined into a single string.

const greeting = 'Hello';
const name = 'John';
const message = greeting + ' ' + name; // Result: 'Hello John'

String Length:

The length property of a string will return the number of characters in the given string datatype.

const str = 'Hello';
console.log(str.length); // Output: 5

JavaScript String Methods:

JavaScript provides various built-in methods to perform operations and manipulate strings.

  • toUpperCase(): Converts a string to uppercase.
  • toLowerCase(): Converts a string to lowercase.
  • concat(): Concatenates two or more strings.
  • substring(): Extracts a portion of a string based on a specified start and end index.
  • charAt(): Returns the character at a specified index in the string.
  • indexOf(): Returns the index of the first occurrence of a specified substring in the string.
  • split(): Splits a string into an array of substrings based on a specified delimiter.
  • trim(): Removes leading and trailing whitespace from a string.
  • replace(): Replaces occurrences of a substring within a string with another substring.

These are some of the commonly used string methods in JavaScript. However, there are many more methods available to manipulate and work with strings.

JavaScript String Comparison:

We can compare strings using comparison operators (<, >, <=, >=, ===, !==).

Immutable nature of JavaScript String data type:

Strings in JavaScript are immutable, meaning that once a string is created, it cannot be changed. Any operation performed on a string creates a new string rather than modifying the original one.

Boolean

Boolean has only two values true andfalse. In many places True is denoted with 1 and False is with 0.

We commonly use boolean in conditional statements like if, else if, and else. These statements evaluate boolean expressions and execute different blocks of code based on the boolean result.

JavaScript has a concept of falsy and truthy values. Falsy values are considered false when evaluated in a boolean context, while truthy values are considered true. Falsy values include false, 0, '' (empty string), null, undefined, and NaN. All other values are considered truthy.

JavaScript Boolean Expressions:

Boolean values can be the result of comparisons or logical operations. Comparison operators (<, >, <=, >=, ===, !==) compare two values and return a boolean result. Logical operators (&&, ||, !) operate on boolean values and produce a boolean result based on their truthiness or falsiness.

Boolean Functions:

JavaScript functions can return boolean values. These functions are typically designed to perform a specific test or check a condition. For example:

function isEven(number) {
return number % 2 === 0;
}

Understanding the boolean data type is fundamental for controlling program flow and implementing conditional logic in JavaScript.

BigInt

The bigint data type is used to represent integers with arbitrary precision, beyond the limits of the regular number data type. It was introduced in ECMAScript 2020 to handle very large numbers that exceed the safe integer range of JavaScript ( -(253-1) to 253-1 or ±9,007,199,254,740,991) number type.

BigInt values have some similarities to Number values, but they also have distinct differences. BigInt values have limitations when it comes to using Math methods and performing operations with Number values. To work with BigInt and Number values together, it is necessary to ensure they are of the same type by explicit type coercion using the respective constructors.

const bigNum = 123n;
const regularNum = 456;
const result = bigNum + BigInt(regularNum);

How to create BigInt values:

To create a bigint value, you append the letter n to the end of an integer literal or use the BigInt() function.

const bigNum1 = 123n;
const bigNum2 = BigInt(456);

BigInt comparison operations:

bigint values can be compared using comparison operators (<, >, <=, >=, ===, !==). When comparing bigint with number values, the bigint values are implicitly converted to number.

const bigNum = 123n;
const regularNum = 456;
const result1 = bigNum > BigInt(regularNum);
const result2 = bigNum === BigInt(regularNum);

BigInt bitwise operations:

BigInt values can also be used in bitwise operations (&, |, ^, ~, <<, >>, >>>), just like regular numbers. However, bitwise operations on bigint values are subject to a maximum of 64 bits.

const bigNum1 = 123n;
const bigNum2 = 456n;
const result = bigNum1 & bigNum2;

Limitations and Considerations in BigInt:

While bigint allows for working with arbitrarily large integers, it's important to note that bigint values are not as performant as regular number values. Also, some operations that are trivial with regular numbers, such as dividing by zero or performing bitwise shifts by a negative value, may throw errors with bigint values.

Symbol

In JavaScript, the Symbol data type represents a unique and immutable value. We can use a symbol as an identifier for object properties.

let one = Symbol("One")
let two = Symbol("One")

console.log(one === two); // Output: false

Symbols were introduced in ECMAScript 2015 (ES6). We can check the type using typeof.

const symbol = Symbol("description");
typeof symbol; // "symbol"

How to create a JavaScript datatype Symbol?

We can create a symbol using the Symbol() function, which returns a unique symbol value. Symbols are guaranteed to be unique, even if they have the same description.

const symbol1 = Symbol();
const symbol2 = Symbol('description');

JavaScript provides several built-in symbols that represent specific behaviors or features. These symbols are accessible as properties of the Symbol constructor and are used in various language-defined operations, such as iteration and customization of object behavior. Examples of well-known symbols include Symbol.iterator, Symbol.toStringTag, and Symbol.hasInstance.

Null

Represents the intentional absence of any object value. It is often used to indicate the lack of a meaningful value.

Null Value:

The null value is a special value that represents the absence of an object. It is often used to indicate that a variable or object property does not currently have a value or points to nothing.

let variable = null;

Type of Null:

The typeof operator applied to null returns an'object'. This behavior is considered a historical quirk in JavaScript, and null is not actually an object.

console.log(typeof null); // Output: 'object'

Null Vs Undefined:

Although null and undefined are often used interchangeably to represent the absence of a value, they have distinct meanings. undefined is the default value assigned to variables that have been declared but not assigned a value, while null is explicitly assigned to indicate no value.

Comparisons with Null:

When comparing null using equality (==) operator, it is equal only to null or undefined. Comparing null with other values will always return false.

console.log(null == null); // Output: true
console.log(null == undefined); // Output: true
console.log(null == 0); // Output: false

Undefined

In JavaScript, the undefined data type represents a variable or object property that has been declared but has not been assigned a value.

The undefined value is a primitive value that is automatically assigned to variables that have been declared but have not been assigned a value. It indicates that the variable does not currently hold a valid value.

let variable;
console.log(variable); // Output: undefined

Type of Undefined:

The typeof operator applied to undefined returns 'undefined'. This provides a way to check if a variable has been assigned a value or not.

console.log(typeof undefined); // Output: 'undefined'

The undefined default value for function:

When a function does not explicitly return a value, it is considered to return undefined by default. Similarly, if an object property is accessed but does not exist, the result will be undefined.

function doSomething() {
// No return statement
}

const obj = {};
console.log(obj.nonExistentProperty); // Output: undefined

Comparisons with Undefined:

When comparing undefined using equality (==) operator, it is equal to both undefined and null. However, comparing undefined with other values will always return false.

console.log(undefined == undefined); // Output: true
console.log(undefined == null); // Output: true
console.log(undefined == 0); // Output: false

Avoiding Undefined:

To avoid undefined values, it is recommended always initialize variables with meaningful values. Assigning an initial value or using appropriate checks and error handling can help prevent unexpected undefined values.

Non-primitive data type in JavaScript.

Object

In JavaScript, objects are non-primitive data types that allow you to store and manipulate collections of key-value pairs. They are versatile and can hold various types of data, including other objects, functions, and primitive values.

Objects can be created using the object literal syntax, which consists of a pair of curly braces {}. Inside the braces, you define one or more key-value pairs separated by colons :. The keys are usually strings, and the values can be any valid JavaScript data type.

const person = {
name: 'John',
age: 30,
isEmployed: true,
sayHello: function() {
console.log('Hello!');
}
};

The keys are unique within an object, and they are used to retrieve or modify the corresponding values.

console.log(person.name); // Output: 'John'
person.age = 31;

Accessing Object Properties:

Object properties can be accessed using dot notation (object.property) or bracket notation (object['property']).

Dot notation is commonly used when the property name is known and is a valid identifier. Bracket notation is useful when the property name is dynamic or contains special characters.

console.log(person.name); // Output: 'John'
console.log(person['age']); // Output: 31

Array

In JavaScript, arrays are non-primitive data types used to store multiple values in a single variable. They are ordered collections of elements and are widely used for storing and manipulating lists of data.

Objects can store array datatypes.

Array syntax:

Arrays can be created using array literal syntax, which involves enclosing the list of elements within square brackets []. Elements are separated by commas.

const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];

Access Array values:

Array elements are accessed using zero-based indexing. Each element in the array has a unique index, starting from 0 for the first element and incrementing by 1 for each subsequent element.

console.log(numbers[0]); // Output: 1
console.log(fruits[2]); // Output: 'orange'

Array Length:

The length property of an array indicates the number of elements it contains.

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5

Array Methods:

Arrays come with a variety of built-in methods that provide convenient ways to perform operations on array elements. Some commonly used array methods include push(), pop(), shift(), unshift(), splice(), slice(), concat(), join(), indexOf(), includes(), sort(), and reverse().

const numbers = [1, 2, 3, 4, 5];
numbers.push(6); // Adds an element to the end
numbers.pop(); // Removes the last element
numbers.shift(); // Removes the first element
numbers.unshift(0); // Adds an element to the beginning
const slicedNumbers = numbers.slice(1, 3); // Creates a new array with a subset of elements
const joinedNumbers = numbers.join(','); // Converts array elements to a string separated by commas

Array Iteration:

Arrays can be iterated using loops such as for loop, for...of loop, or array methods like forEach(), map(), filter(), and reduce(). These allow you to perform operations on each element of the array or transform the array into a new form.

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

numbers.forEach(function(number) {
console.log(number);
});

const doubledNumbers = numbers.map(function(number) {
return number * 2;
});

Function

In JavaScript, functions are non-primitive data types that allow you to define reusable blocks of code. They can be assigned to variables, passed as arguments to other functions, and returned as values from other functions.

Functions play a crucial role in JavaScript as they enable code organization, encapsulation, and reusability.

Functions can be declared using the function keyword followed by a function name, a list of parameters enclosed in parentheses, and a block of code enclosed in curly braces.

function greet(name) {
console.log('Hello, ' + name + '!');
}

Function Invocation:

Functions can also be defined as function expressions by assigning an anonymous function to a variable. Function expressions can be named or anonymous.

Functions are invoked or called using parentheses () after the function name. Arguments can be passed to the function inside the parentheses.

const greet = function(name) {
console.log('Hello, ' + name + '!');
};

greet('John'); // Output: 'Hello, John!'

Return statement in Function:

Functions can return a value using the return statement. The return statement ends the function execution and specifies the value to be returned to the caller.

Parameters in Function:

Functions can accept parameters, which act as placeholders for values passed during function invocation. Parameters are specified within the function declaration or expression and are separated by commas.

function multiply(a, b) {
return a * b;
}

const result = multiply(2, 3); // result = 6

Function Scope:

Functions have their own scope, meaning that variables defined inside a function are only accessible within that function unless they are explicitly returned or accessed through closures.

function greet(name) {
const message = 'Hello, ' + name + '!';
console.log(message);
}

greet('John'); // Output: 'Hello, John!'
console.log(message); // Error: 'message' is not defined

Anonymous Functions:

JavaScript supports anonymous functions, which are functions without a name. Anonymous functions are often used as callback functions or immediately invoked function expressions (IIFE).

setTimeout(function() {
console.log('Delayed message');
}, 1000);

Reference

When it comes to JavaScript, understanding data types is crucial for effective programming. In this article, I’ve consolidated my knowledge on JavaScript Data Types from diverse sources including geeksforgeeks.org, w3schools.com, Mozilla Developers, studytonight.com, ChatGPT, Google Search, and more. If there’s anything I’ve overlooked or if you have additional insights to share, I encourage you to join the discussion in the comment section. Let’s enhance our understanding of JavaScript data types together!

--

--

Karthik Shetty

Web developer & tech enthusiast sharing insights on coding, web tools, and the ever-evolving IT landscape. Let's code together! 🚀