• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Check if the provided value is of the specified type

Check if the provided value is of the specified type

Check if the provided value is of the specified type

Ensure the value is not undefined or null using Array.prototype.includes(). Compare the constructor property on the value with type to check if the provided value is of the specified type.

const is = (type, val) => ![, null].includes(val) && val.constructor === type;

// Examples
is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true

Source

https://www.30secondsofcode.org/js/s/is

Miscellaneous

Related Snippets:

  • Count the occurrences of a value in an array
  • How To Import A JavaScript File In Another JavaScript File
  • Find the difference between two arrays with JavaScript
  • Add characters to the end of a string if it’s less than a certain length

Primary Sidebar

JSON Compare

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers
Advertisement