乐闻世界logo
搜索文章和话题

What are the two data types categories in Node.js?

1个答案

1

In Node.js, data types are primarily categorized into two main types: Primitive Types and Reference Types.

Primitive Types

Primitive types are stored directly in the Stack. These types include:

  • Number: Used for representing integers or floating-point numbers, such as 123 or 3.14.
  • String: Used for representing text, such as "Hello, World!".
  • Boolean: Represents logical truth values, with only two values, true and false.
  • Undefined: When a variable is declared but not assigned a value, its value is undefined.
  • Null: Represents the absence of any value, typically used to indicate empty or non-existent values.
  • Symbol: A type introduced in ES6, used for creating unique identifiers.

Reference Types

Reference types are stored in the Heap, accessed via pointers stored in the Stack. These types include:

  • Object: The most basic reference type, capable of storing multiple values of different types within an object. For example:
    javascript
    let person = { name: "Alice", age: 25 };
  • Array: Used for storing ordered collections of data. For example:
    javascript
    let numbers = [1, 2, 3, 4, 5];
  • Function: Functions are also object types, which can be assigned to variables and have properties and methods. For example:
    javascript
    function greet(name) { return "Hello, " + name + "!"; }

Example In real-world development, we frequently handle various data types. For instance, when writing a function to process user input data and store it in a database, you might use strings (for user names and addresses), numbers (for age or phone numbers), and even objects to organize this data, as shown below:

javascript
function storeUserData(name, age, address) { let userData = { userName: name, userAge: age, userAddress: address }; database.save(userData); }

In this example, name, age, and address are passed as arguments to the function using primitive types, while userData is an object used to consolidate these data and store them as a single unit.

2024年8月6日 00:03 回复

你的答案