Data Types in JavaScript

In JavaScript, data types are how we categorize different types of data that we can work with in our programs. Understanding data types is fundamental to writing effective and bug-free code. JavaScript has several built-in data types, which can be categorized into two main groups: primitive data types and non-primitive (reference) data types.

Primitive Data Types

1. Number

  • Represents numeric data, both integers and floating-point numbers.

  • Example: let num = 10;

2. String

  • Represents a sequence of characters, enclosed within single or double quotes.

  • Example: let name = "John";

3. Boolean

  • Represents a logical entity, either true or false.

  • Example: let isLogged = true;

4. Undefined

  • Represents a variable that has been declared but not assigned a value.

  • Example: let data;

5. Null

  • Represents an intentional absence of any object value.

  • Example: let value = null;

6. Symbol (ES6)

  • Represents a unique identifier, often used to create object properties that won't collide with other properties.

  • Example: const sym = Symbol();

Non-Primitive (Reference) Data Types

1. Object

  • Represents a collection of key-value pairs.

  • Example: let person = { name: "Alice", age: 30 };

2. Array

  • Represents a collection of elements, ordered and indexed starting from zero.

  • Example: let numbers = [1, 2, 3, 4, 5];

3. Function

  • Represents reusable blocks of code that can be called to perform a specific task.

  • Example:

    function greet(name) {
        console.log(`Hello, ${name}!`);
    }

4. Date

  • Represents a specific point in time, with various methods to work with dates and times.

  • Example: let today = new Date();

5. RegExp

  • Represents a regular expression, used for pattern matching within strings.

  • Example: let pattern = /\w+/;

6. Map and Set (ES6)

  • Map represents a collection of key-value pairs with unique keys.

  • Set represents a collection of unique values.

  • Examples:

    let myMap = new Map();
    let mySet = new Set();

7. Custom Objects

  • JavaScript allows developers to define custom objects using constructor functions or classes.

  • Example:

    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    let person1 = new Person("Bob", 25);

Understanding these data types and how they behave in JavaScript is crucial for writing efficient and bug-free code. Each data type has its own set of properties and methods that can be utilized to manipulate and work with data effectively.

Last updated