# 原始值

在 JavaScript 中，原始值是指不是对象也没有方法的数据。

* primitive value，原始值，ECMAScript 规范里出现的频次较高 \~ `data value`
* primitive data type，原始数据类型 \~ 原始类型，简称类型 \~ `data type`
* primitive 原语。大约是原始值和原始类型的统称，具体看上下文

## 7个原始值

JavaScript 有 7 个原始值，分别对应 7 个原始类型。其中，除了 Undefined 和 Null 之外，其它数据类型都有一个等价的对象包装器，包装器的 `valueOf()` 方法会返回原始值。

| Primitive Value | Primitive Type | Object  |
| --------------- | -------------- | ------- |
| undefined       | Undefined      | -       |
| null            | Null           | -       |
| Boolean         | Boolean        | Boolean |
| String          | String         | String  |
| Number          | Number         | Number  |
| BigInt          | BigInt         | BigInt  |
| Symbol          | Symbol         | Symbol  |

## 理解原始值

很多时候，在语言实现的最底层，原始值都是直接表示的。

### 不可变

所有的原始值都是不可变的——不能被改变。

> Primitive values are immutable.

```javascript
// 使用字符串方法，不会改变字符串本身
let foo = 'JavaScript';
console.log(foo);    // JavaScript
foo.toUpperCase();  // JAVASCRIPT
console.log(foo)    // JavaScript
```

### 原始值 vs 变量

在动态语言里，值是有类型的，但是变量没有（类型）。

切记，不要混淆原始值本身和分配了原始值的变量。变量是可以被重新分配新值的，而已经存在的原始值是不能被修改的。如下：

```javascript
// 给变量重新赋一个“新”值，而不是“突变/变异”值（mutated 生物学术语）
let foo = 'JavaScript';
foo = foo.toUpperCase();
console.log(foo);  // JAVASCRIPT
```

### 原始值 vs 对象

对象、数组和函数的值之所以能被修改，是因为它们不是原始值。

如前所述“原始值是指不是对象也没有方法的数据”。举个例子感受下原始值和对象的不同，如下：

```javascript
// 在 JavaScript 中，数组和函数都是对象
let bar = [];
console.log(bar);  // []
bar.push('JavaScript'); // push() 会改变数组本身
console.log(bar);  // ["JavaScript"]
```

## 总结

这部分列出了 JavaScript 里的 7 个原始值，并着重介绍了原始值的不可变性、原始值和变量的区别，以及原始值和对象的区别。

## 主要参考

* <https://developer.mozilla.org/en-US/docs/Glossary/primitive>
* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures>
* <https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://anjia1.gitbook.io/web/js/data-type/primitive-value.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
