In Node.js, you have various data types that you can use to store and manipulate different kinds of data. Here are some of the common data types with examples:
Number:
Used for numeric values like integers and floating-point numbers.
const age = 30;
const price = 19.99;
String:
Used for text and character data.
const name = "John Doe";
const message = "Hello, world!";
Boolean:
Represents true or false values.
const isActive = true;
const isLoggedIn = false;
Array:
Stores multiple values in an ordered list.
const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "orange"];
Object:
A collection of key-value pairs, used to represent entities and complex data structures.
const person = {
name: "Alice",
age: 25,
isEmployed: true,
};
Function:
A block of reusable code that can be called with arguments and returns a value.
function add(a, b) {
return a + b;
}
const multiply = function (x, y) {
return x * y;
};
Null:
Represents the intentional absence of a value.
const data = null;
Undefined:
Represents the absence of a value (typically used for uninitialized variables).
let value;
Symbol:
Represents a unique identifier, often used for object properties.
const key = Symbol("myKey");
const obj = {
[key]: "some value",
};
Date:
Represents a specific point in time.
const currentDate = new Date();
Buffer:
Used to handle binary data, typically for working with streams and files.
const bufferData = Buffer.from("Hello, world!", "utf-8");
Map:
A collection of key-value pairs where the keys can be of any data type.
const myMap = new Map();
myMap.set("name", "John");
myMap.set(1, "One");
Set:
A collection of unique values.
const mySet = new Set();
mySet.add("apple");
mySet.add("banana");
mySet.add("apple"); // Ignored, as it's a duplicate
These are some of the commonly used data types in Node.js. Depending on the application's requirements, you might also encounter other data types like Buffers, Promises, Regular Expressions, etc. Understanding these data types is crucial for writing effective JavaScript code in Node.js.
Top comments (0)