JavaScript Data Types

In JavaScript, data types refer to the classification of different types of data such as numbers, strings, objects, etc., that can be used in the code. JavaScript is a dynamically typed language, which means you don’t need to specify the type of a variable when declaring it. JavaScript automatically determines the data type based on the value assigned to the variable.

Types of JavaScript Data Types:

Primitive Data Types in JavaScript:

Non-Primitive Data Types in JavaScript:

How to Check the Type of a Variable:

JavaScript provides the typeof operator, which can be used to check the data type of a variable. The result will be a string representing the type of the variable.

Syntax


let age = 25;
console.log(typeof age); // Output: number

Example of Checking Data Types:

This example shows how to check different types using the typeof operator.

Example 1


let name = "John";
let age = 25;
let isStudent = true;
            
console.log(typeof name); // Output: string
console.log(typeof age); // Output: number
console.log(typeof isStudent); // Output: boolean

Output:

string
number
boolean

Primitive vs Non-Primitive Data Types:

Example of Object Data Type:

Objects are collections of key-value pairs. An object can represent real-world entities like a car or a person.

Example 2


let person = {
    name: "John",
    age: 25,
    isStudent: true
};
            
console.log(typeof person); // Output: object

Output:

object

Type Conversion:

Sometimes, you may want to convert one type of data to another. In JavaScript, you can use String(), Number(), and Boolean() to perform type conversions.

Example 3


let str = "123";
let num = Number(str); // Convert string to number
console.log(typeof num); // Output: number

Output:

number

Common Operations with JavaScript Data Types: