Data Types in Node.js
Understand JavaScript data types: primitives, reference types, type checking, comparisons, and validations.
What Are Data Types?
Data types define what kind of value a variable can hold. JavaScript is dynamically typed, meaning types are decided at runtime.
1. Dynamic Typing
Variables can change their data type.
Primitive Data Types
Primitive data types store immutable values and are copied by value.
1. String
Textual data.
2. Number
Integer and floating-point numbers.
3. Boolean
true or false.
4. Undefined
Declared but not assigned.
5. Null
Intentional absence of value.
6. BigInt
Very large integers.
7. Symbol
Unique identifiers.
Reference Data Types
Reference types are copied by reference, not by value.
1. Object
Key-value pairs.
2. Array
Ordered list of values.
3. Function
Callable object.
Printing the Data Type
JavaScript provides the typeof operator to inspect data types.
1. Using typeof
Check the type of a value.
Comparing Data Types
You can compare data types using typeof in if-else or switch.
1. Type Check Using if-else
Compare types using typeof.
2. Type Check Using switch
Switch based on typeof.
Checking Arrays, Objects, and Functions
typeof alone is not enough for arrays and objects.
1. Checking if a Variable is an Array
Use Array.isArray().
2. Checking if a Variable is a Specific Object
Use classes and instanceof to check for a specific object type.
3. Checking if a Variable is a Function
Use typeof.