What is data type in JavaScript and how many types?
In JavaScript, a data type is a type of value that can be stored in a variable. There are a total of 7 data types in JavaScript:
- Number: used to represent numeric values, including integers and floating-point numbers.
- String: used to represent sequences of characters, such as words or sentences.
- Boolean: used to represent the truth values of true or false.
- Null: used to represent an intentional non-value.
- Undefined: used to represent an uninitialized value.
- Object: used to represent collections of data and properties, as well as methods.
- Symbol: used to represent unique and immutable data types.
There are two main categories of data types: primitive and non-primitive.
Primitive data types are the basic data types that form the building blocks of the language. They include:
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
These data types are simple, immutable, and have a direct value stored in the memory. When a primitive value is assigned to a variable, the value is stored directly in the memory and not as an object reference.
On the other hand, non-primitive data types are more complex and dynamic. They are objects, which are instances of object constructors, and include:
- Object
- Array
- Function
- RegExp (regular expression)
These data types are mutable, meaning that their properties and values can be changed after they have been created. When a non-primitive value is assigned to a variable, the variable stores a reference to the object in the memory, rather than the actual value itself.