# valueToString()

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [value](https://lochiwei.gitbook.io/web/js/val) ⟩ [type](https://lochiwei.gitbook.io/web/js/val/type) ⟩ [conversion](https://lochiwei.gitbook.io/web/js/val/type/convert) ⟩ 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](https://lochiwei.gitbook.io/web/js/val/type/type-functions/isobject "mention")

```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](https://lochiwei.gitbook.io/web/appendix/custom/helper-functions) (0.1.8)
* [str](https://lochiwei.gitbook.io/web/js/val/prim/str "mention")
  {% endtab %}
  {% endtabs %}


---

# 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://lochiwei.gitbook.io/web/js/val/obj/convert/valuetostring.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.
