# isPrimitive()

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [values](https://lochiwei.gitbook.io/web/js/val) ⟩ [custom functions](https://lochiwei.gitbook.io/web/js/val/type/type-functions) ⟩ isPrimitive()

{% hint style="success" %}
check if [..](https://lochiwei.gitbook.io/web/js/val "mention") is a [prim](https://lochiwei.gitbook.io/web/js/val/prim "mention").
{% endhint %}

{% tabs %}
{% tab title="🗺️ 圖表" %}

* replit：[isPrimitive()](https://replit.com/@pegasusroe/isPrimitivevalue#isPrimitive.js)

```javascript
┌── (primitive ?)
│  typeof       type         expr         value       
---------------------------------------------------------------------
✅ object       Null         null         null
---------------------------------------------------------------------
✅ undefined    Undefined    undefined    undefined
---------------------------------------------------------------------
✅ number       Number       37           37
✅ number       Number       3.14         3.14
✅ number       Number       Math.LN2     0.6931471805599453
✅ number       Number       Infinity     Infinity ⭐️
✅ number       Number       NaN          NaN ⭐️
✅ number       Number       Number('1')  1
✅ number       Number       Number('ab') NaN
---------------------------------------------------------------------
✅ bigint       BigInt       42           42n
---------------------------------------------------------------------
✅ string       String       'bla'        'bla'
✅ string       String       `x = ${1+2}` 'x = 3'
✅ string       String       typeof 1     'number'
✅ string       String       String({})   '[object Object]'
✅ string       String       typeof xxx   'undefined'
---------------------------------------------------------------------
✅ boolean      Boolean      true         true
✅ boolean      Boolean      Boolean(1)   true
✅ boolean      Boolean      !!(1)        true
---------------------------------------------------------------------
✅ symbol       Symbol       Symbol()     Symbol()
✅ symbol       Symbol       Symbol.iterator Symbol(Symbol.iterator)
---------------------------------------------------------------------
❌ object       Object       {a:1}        { a: 1 }
❌ object       User         user         User { name: 'JohnDoe' }
❌ object       Array        [1, 2]       [ 1, 2 ]
❌ object       Date         new Date()   2022-09-13T01:47:46.344Z
❌ object       RegExp       /regex/      /regex/
---------------------------------------------------------------------
❌ function     Function     function(){} [Function (anonymous)]
❌ function     Function     Math.sin     [Function: sin]
❌ function     Function     () => {}     [Function (anonymous)]
❌ function     class        class {}     [class (anonymous)]
❌ function     class        User         [class User]
❌ function     GeneratorFunction function*(){} [GeneratorFunction (anonymous)]
---------------------------------------------------------------------
```

{% endtab %}

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

* replit：[isPrimitive()](https://replit.com/@pegasusroe/isPrimitivevalue#isPrimitive.js)

```javascript
// ⭐ check if value is object
function isObject(value) {
    return value === Object(value)
}

// ⭐ check if value is primitive
function isPrimitive(value) {
    return !isObject(value)
}

// export
module.exports = { isObject, isPrimitive };
```

{% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}
[infinity](https://lochiwei.gitbook.io/web/js/val/prim/num/special/infinity "mention"), [nan](https://lochiwei.gitbook.io/web/js/val/prim/num/special/nan "mention") are [primitives](https://lochiwei.gitbook.io/web/js/val/prim).
{% endhint %}

{% hint style="success" %}
The [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) <mark style="color:yellow;">**constructor**</mark>'s behavior <mark style="color:orange;">**depends**</mark> on the <mark style="color:yellow;">**input's type**</mark>, if the <mark style="color:yellow;">**value**</mark> is

* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)：<mark style="color:yellow;">**empty object**</mark> is returned.
* an <mark style="color:yellow;">**object**</mark> already：the value <mark style="color:orange;">**itself**</mark> is returned.
* otherwise：<mark style="color:yellow;">**object of a**</mark>**&#x20;**<mark style="color:orange;">**Type**</mark> that <mark style="color:yellow;">**corresponds to the value**</mark> is returned.
  {% endhint %}

{% hint style="warning" %} <mark style="color:blue;">`Object(value)`</mark> is <mark style="color:orange;">**identically**</mark> to <mark style="color:blue;">`new Object(value)`</mark>
{% endhint %}
{% endtab %}

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

* [isobject](https://lochiwei.gitbook.io/web/js/val/type/type-functions/isobject "mention") - check if value is an [obj](https://lochiwei.gitbook.io/web/js/val/obj "mention").
  {% endtab %}

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

* replit：[isPrimitive()](https://replit.com/@pegasusroe/isPrimitivevalue#isPrimitive.js)
* require：test cases from [typename](https://lochiwei.gitbook.io/web/js/val/type/name/typename "mention")

```javascript
// ⭐ import (functions for type name)
const { typeName, baseTypeName } = require('./typeNames.js');
const { testCases } = require('./testCases.js');
const { isPrimitive } = require('./isPrimitive.js');

// table settings
const header = ['typeof', 'type', 'expr', 'value'];
const cols = header.length;
const [width, pad, ext] = [12, 1, 18];
const line = '-'.repeat(width*cols + pad*(cols-1) + ext);

// header
console.log('  ', ...header.map(s => s.padEnd(width, ' ')));
console.log(line);

// rows
for (const testCase of testCases) {

    // separator
    if (testCase === '---') {
        console.log(line); 
        continue; 
    }
    
    // test cases
    const value = testCase[0];
    const expr = testCase[1] || String(testCase[0]);

    const types = [typeof value, typeName(value)];
    const numberOfDifferentTypes = new Set(types.map(s => s.toLowerCase())).size;

    console.log(
         isPrimitive(value) ? '✅' : '❌',
        ...[...types, expr].map(s => s.padEnd(width, ' ')),
        value,
    )
}

console.log(line);

// legend
console.log(`• ⭐️ types not all the same        • ❗ base !== type`);
```

{% endtab %}

{% tab title="📘 手冊" %}

* [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
  {% endtab %}

{% tab title="⬇️ 應用" %}

* [print](https://lochiwei.gitbook.io/web/js/val/obj/proto/chain/print "mention") - print the [chain](https://lochiwei.gitbook.io/web/js/val/obj/proto/chain "mention") of an [obj](https://lochiwei.gitbook.io/web/js/val/obj "mention").
  {% endtab %}

{% tab title="🗣 討論" %}

* [Check if a value is an object in JavaScript](https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript)
* [test if a variable is a primitive rather than an object?](https://stackoverflow.com/questions/31538010/test-if-a-variable-is-a-primitive-rather-than-an-object)
  {% 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/type/type-functions/isprimitive.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.
