> 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/type/type-functions/isprimitive.md).

# isPrimitive()

[JS](/web/js.md) ⟩ [values](/web/js/val.md) ⟩ [custom functions](/web/js/val/type/type-functions.md) ⟩ isPrimitive()

{% hint style="success" %}
check if [value](/web/js/val.md) is a [primitive](/web/js/val/prim.md).
{% 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](/web/js/val/prim/num/special/infinity.md), [NaN](/web/js/val/prim/num/special/nan.md) are [primitives](/web/js/val/prim.md).
{% 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()](/web/js/val/type/type-functions/isobject.md) - check if value is an [object](/web/js/val/obj.md).
  {% endtab %}

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

* replit：[isPrimitive()](https://replit.com/@pegasusroe/isPrimitivevalue#isPrimitive.js)
* require：test cases from [typeName()](/web/js/val/type/name/typename.md)

```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="⬇️ 應用" %}

* [printPrototypeChain()](/web/js/val/obj/proto/chain/print.md) - print the [prototype chain](/web/js/val/obj/proto/chain.md) of an [object](/web/js/val/obj.md).
  {% 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 %}
