> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/obj/convert/valuetostring.md).

# valueToString()

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [type](/web/js/val/type.md) ⟩ [conversion](/web/js/val/type/convert.md) ⟩ valueToString()

{% hint style="success" %}
convert a value to its most "natural" string representation.
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit： [valueToString()](https://replit.com/@pegasusroe/valueToString#index.js),  require：[isObject()](/web/js/val/type/type-functions/isobject.md)

```javascript
const { isObject } = require('./isObject.js');

// ⭐️ valueToString(value)
function valueToString(value){

    const str = String(value);

    // ------------ primitive ------------
    
    if (!isObject(value)) {
        if (typeof value === 'string') return `'${str}'`;
        return str;
    }

    // ------------ object ------------

    // array
    if (Array.isArray(value)) return '[' 
        + value.map(x => valueToString(x)).join(',')
        + ']';
    
    // Set
    if (str === '[object Set]') 
        return `{${[...value].map(x => valueToString(x)).join(', ')}}`;
    
    // Map
    if (str === '[object Map]') 
        return `{${[...value].map(p => `${p[0]}→${valueToString(p[1])}`).join(', ')}}`;
    
    // function: return its code
    if (typeof value === 'function') return value.toString();
    
    // other object, try to get its methods as well.
    let result = [];
    
    for (let key in value) {
        result.push(`${key}: ${valueToString(value[key])}`);
    }
    
    return `{${result.join(', ')}}`;
}

// export
module.exports = { valueToString };
```

💈範例：

```javascript
string               value
--------------------------------------------------
''                   ''
'yes'                'yes'
'0'                  '0'
'3'                  '3'
'+5'                 '+5'
'-4.3'               '-4.3'
--------------------------------------------------
true                 true
false                false
--------------------------------------------------
0                    0
5.6                  5.6
-7.8                 -7.8
NaN                  NaN
--------------------------------------------------
null                 null
undefined            undefined
--------------------------------------------------
[]                   []
[0]                  [ 0 ]
[4.6]                [ 4.6 ]
[2,3]                [ 2, 3 ]
[1,2,3,4]            [ [ 1, 2 ], [ 3, 4 ] ]
--------------------------------------------------
{1, 'hi'}            Set(2) { 1, 'hi' }
--------------------------------------------------
{x→0}                Map(1) { 'x' => 0 }
--------------------------------------------------
{}                   {}
{a: 2}               { a: 2 }
{a: 2, f: () => 1}   { a: 2, f: [Function: f] }
--------------------------------------------------
() => true           [Function (anonymous)]
() => 1              [Function (anonymous)]
--------------------------------------------------
```

{% endtab %}

{% tab title="💈範例" %}

* codepen ⟩ [object.toString() ?](https://codepen.io/lochiwei/pen/vYJGooO?editors=0011)
* codesandbox ⟩ [compare: \~\~, +, !!, Math.trunc](https://codesandbox.io/s/compare-math-trunc-bi2gh?file=/src/styles.css:0-232)

{% embed url="<https://codesandbox.io/embed/compare-math-trunc-bi2gh?fontsize=14&hidenavigation=1&theme=dark>" %}
toString(obj): first column
{% endembed %}
{% endtab %}

{% tab title="👥 相關" %}

* [helper functions](/web/appendix/custom/helper-functions.md) (0.1.8)
* [String](/web/js/val/prim/str.md)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/obj/convert/valuetostring.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
