• 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:

  • Get the index of the first matching item in an array
  • Combine two arrays using the spread operator
  • Check if at least one element of values is included in arr
  • Get size of the selected file

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us