JavaScript Data Types

JavaScript provides a set of data types that can be used to store and manipulate data. These types are divided into primitive and non-primitive types.

1. Primitive Data Types

Primitive data types are basic types that are not objects and have no methods. They are immutable and passed by value.

  • String: Represents a sequence of characters. Example: "Hello, World!"
  • Number: Represents both integer and floating-point numbers. Example: 42, 3.14
  • BigInt: Represents whole numbers larger than 253 - 1. Example: 1234567890123456789012345678901234567890n
  • Boolean: Represents a logical entity and can have two values: true or false
  • Undefined: Represents a variable that has been declared but not yet assigned a value. Example: let x;
  • Null: Represents the intentional absence of any value. Example: let x = null;
  • Symbol: Represents a unique and immutable value used as an object property key. Example: Symbol('description')

2. Non-Primitive Data Types

Non-primitive data types are objects, which are mutable and passed by reference.

  • Object: A collection of key-value pairs. Example: { name: "John", age: 30 }
  • Array: A list-like object that can hold multiple values. Example: [1, 2, 3, 4]
  • Function: A callable object that performs a specific task. Example: function greet() { return "Hello"; }
  • Date: Represents date and time. Example: new Date()

3. Type Conversion

JavaScript performs automatic type conversion between different types. You can also convert types explicitly using methods.

  • String to Number: Number("123") converts a string to a number.
  • Number to String: String(123) converts a number to a string.
  • Boolean Conversion: Use Boolean(value) to convert a value to a Boolean.

4. Typeof Operator

The typeof operator returns a string indicating the type of the operand.

typeof "Hello" returns "string"

typeof 123 returns "number"

typeof true returns "boolean"

typeof {} returns "object"

typeof undefined returns "undefined"

typeof Symbol() returns "symbol"