JavaScript Data Types

JavaScript Data Types

Learn about different JavaScript data types, how they work, and how to use them effectively in real-world applications.

Introduction

JavaScript is a versatile and widely used programming language that enables developers to build dynamic, interactive, and user-friendly web applications. Despite the similarity in their names, Java and JavaScript are completely different languages with distinct purposes, syntax, and use cases. To get the most out of JavaScript, a basic understanding of HTML and CSS is strongly recommended, as they form the core structure and styling of modern websites.

JavaScript runs directly in the web browser and follows the ECMAScript standard, making it a fundamental technology for front-end web development. It allows developers to manipulate web page content in real time, respond to user actions, validate forms, control multimedia, and create engaging user experiences without reloading the page.

Today, JavaScript is also used beyond the browser with platforms such as Node.js, enabling developers to build scalable server-side applications. Due to its flexibility, performance, and widespread industry adoption, JavaScript has become one of the most essential skills for web developers worldwide.

What Are Data Types in JavaScript?

In JavaScript, data types specify the type of value that a variable can hold. They allow the JavaScript engine to correctly interpret data, manage memory efficiently, and determine which operations can be performed on a value during program execution.

JavaScript is a dynamically typed language, meaning variables do not require an explicit data type declaration. Instead, the data type is automatically determined at runtime based on the assigned value.

JavaScript supports two main categories of data types: primitive and non-primitive (reference). Common primitive data types include Number, String, Boolean, Undefined, and Null, while non-primitive types are used to store more complex data structures.

Data Types in JavaScript

  • Number – Represents both integers and floating-point numbers, including positive and negative values
  • String – Used to store and manipulate textual data enclosed in single, double, or backticks quotes
  • Boolean – Represents logical values: true or false
  • Undefined – Indicates that a variable has been declared but has not yet been assigned a value
  • Null – Represents an intentional absence of any object value, often used to reset or clear a variable

Number Data Type in JavaScript

The Number data type in JavaScript is a primitive data type used to represent numeric values. It supports both whole numbers (integers) and decimal values (floating-point numbers). Unlike many other programming languages, JavaScript uses a single numeric type and does not distinguish between integers, floats, or double-precision numbers.

JavaScript numbers are based on the IEEE 754 double-precision floating-point format, which allows them to represent very large or very small values. In addition to standard numeric values, JavaScript also provides special numeric values such as Infinity and NaN (Not a Number), which are commonly encountered during mathematical calculations and error handling.

Example: JavaScript Number Data Type

// Integer number
let a = 12;
console.log(a);

// Floating-point number
let b = 10.3;
console.log(b);

// Infinity value
let c = Infinity;
console.log(c);

// Invalid number operation (NaN)
let d = 'something here too' / 2;
console.log(d);
        
Try it Yourself »

String Data Type in JavaScript

The String data type is a fundamental primitive data type in JavaScript. A string represents an ordered sequence of characters and is widely used to store textual information such as names, email addresses, messages, labels, and user input.

JavaScript supports three ways to define strings: single quotes, double quotes, and template literals (backticks). Template literals are especially powerful because they allow string interpolation, making it easy to embed variables and expressions directly within a string.

Example: JavaScript String Data Type

// Using double quotes
let firstName = "John";
console.log(firstName);

// Using single quotes
let country = 'United Kingdom';
console.log(country);

// Using template literals (backticks)
let age = 25;
let introduction = `My name is ${firstName}, I am ${age} years old, and I live in the ${country}.`;
console.log(introduction);
        
Try it Yourself »

Example: Using Quotes Inside Strings in JavaScript

When quotation marks are used inside strings, JavaScript may interpret them as the end of the string, which can lead to syntax errors. To handle this correctly, developers typically use different types of quotes or apply escape characters ( \ ) to explicitly define how the string should be read.

JavaScript Example

// Single quote inside double quotes
let sentence1 = "It's a beautiful day";
console.log(sentence1);

// Double quotes inside single quotes
let sentence2 = 'She said, "JavaScript is awesome!"';
console.log(sentence2);

// Escaping double quotes using backslash
let sentence3 = "He said, \"Learning JavaScript is fun\"";
console.log(sentence3);
        
Try it Yourself »

Boolean Data Type in JavaScript

The Boolean data type represents logical values and can hold only two values: true and false. Booleans are commonly used in conditions, authentication checks, and form validation.

JavaScript Example

// Boolean values
let isLoggedIn = true;
console.log(isLoggedIn);

let hasPermission = false;
console.log(hasPermission);
        
Try it Yourself »

Undefined Data Type in JavaScript

In JavaScript, a variable has the value undefined when it is declared but has not been assigned a value. This often occurs when a variable is created without initialization or when a function does not explicitly return a value.

The undefined value is automatically assigned by JavaScript and indicates the absence of a defined value, helping developers detect uninitialized variables and potential logic errors during program execution.

JavaScript Example

// Variable declared but not initialized
let username;
console.log(username);

// Function without a return statement
function getUserAge() {
    // no return value
}
console.log(getUserAge());
        
Try it Yourself »

Null Data Type in JavaScript

The null data type represents the intentional absence of any value. It is explicitly assigned by developers to indicate that a variable currently holds no meaningful data, but may receive a value later. This is commonly used when clearing variables, resetting application state, or handling optional data.

Unlike undefined, which is assigned automatically by JavaScript, null is deliberately set by the programmer and clearly communicates intent.

JavaScript Example

// User profile initially has no data
let userProfile = null;
console.log(JSON.stringify(userProfile));

// Later, when data becomes available
userProfile = {
    name: "Emma",
    country: "Canada",
    isVerified: true
};
console.log(JSON.stringify(userProfile));

// Resetting the profile (e.g., on logout)
userProfile = null;
console.log(JSON.stringify(userProfile));
        
Try it Yourself »

Non-Primitive Data Types in JavaScript

Non-primitive data types, also referred to as reference types, are used to store complex data structures and collections of related values. Unlike primitive types, they are stored and accessed by reference, meaning that multiple variables can reference the same object in memory. Common non-primitive data types in JavaScript include Objects, Arrays, and Functions.

Object Data Type in JavaScript

The Object data type is used to store structured data in the form of key–value pairs. Objects are a core building block of JavaScript and are commonly used to represent real-world entities such as users, companies, products, application settings, and configuration data.

Object values can include primitive data types, other objects, arrays, and even functions (methods), making objects highly flexible and powerful.

JavaScript Example

// Creating an object with nested data and a method
let company = {
    name: "TCS",
    industry: "Information Technology",
    headquarters: {
        city: "Bangalore",
        country: "India"
    },
    employees: 2500,
    isHiring: true,
    getSummary: function () {
        return `${this.name} operates in the ${this.industry} sector and is currently hiring: ${this.isHiring}`;
    }
};

// Accessing object properties
console.log(company.name);
console.log(company.headquarters.city);
console.log(company.getSummary());
        
Try it Yourself »

Array Data Type in JavaScript

An Array is a special type of object in JavaScript used to store multiple values within a single variable. Arrays preserve the order of elements and can contain values of different data types, including numbers, strings, objects, and even other arrays. They are commonly used to manage lists of data such as users, products, or application records.

JavaScript Example

// Array of user names
let users = ["Alice", "John", "Maria", "David"];

// Accessing array elements
console.log(users[0]);
console.log(users[2]);

// Adding a new element to the array
users.push("Sophia");
console.log(users);

// Array containing mixed data types
let userProfile = [
    "Emma",
    28,
    { country: "Canada", isActive: true },
    ["JavaScript", "React", "Node.js"]
];
console.log(userProfile);
        
Try it Yourself »

Function in JavaScript

A function in JavaScript is a reusable block of code designed to perform a specific task. Functions allow developers to organize logic, avoid code duplication, and write cleaner, more maintainable applications. In JavaScript, functions are treated as first-class objects, meaning they can be stored in variables, passed as arguments, and returned from other functions.

JavaScript Example

// Defining a function with parameters
function greetUser(name, country) {
    return `Hello ${name}! Welcome from ${country}.`;
}

// Calling the function
console.log(greetUser("Alice", "United States"));
console.log(greetUser("Daniel", "United Kingdom"));
        
Try it Yourself »

Date Object in JavaScript

The Date object in JavaScript is used to work with dates and time values. It enables developers to create, manipulate, compare, and format dates for tasks such as timestamps, scheduling, logging events, and displaying local time.

JavaScript stores dates internally as the number of milliseconds since January 1, 1970 (UTC), commonly known as the Unix Epoch.

JavaScript Example

// Creating a Date object for the current date and time
let currentDate = new Date();

// Getting individual date components
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // Months are zero-based
let day = currentDate.getDate();

// Displaying formatted date
console.log(`Today's date is: ${day}/${month}/${year}`);

// Displaying current time
console.log(currentDate.toLocaleTimeString());
        
Try it Yourself »

Regular Expression in JavaScript

A Regular Expression (RegExp) in JavaScript is a powerful pattern-matching tool used to search, match, and validate text. Regular expressions are widely used in real-world applications for tasks such as form validation, filtering user input, searching within strings, and performing advanced string manipulation.

JavaScript supports regular expressions through built-in methods such as test(), match(), and replace(), along with optional flags like i (case-insensitive) and g (global search).

JavaScript Example

// Case-insensitive pattern to check for the word "javascript"
let pattern = /javascript/i;

// Testing the pattern against a string
let text = "I am learning JavaScript programming";
let result = pattern.test(text);

console.log(result); // true

// Validating an email address
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
let email = "user@example.com";

console.log(emailPattern.test(email)); // true
        
Try it Yourself »

Tip: Regular expressions are case-sensitive by default. Use the i flag (for example, /hello/i) to perform a case-insensitive match.