As I was improving the next version of jPaq, I realized that another simple type checking function that I need is one that will indicate whether or not the specified argument is a primitive. believe it or not, the code to do this test is quite simple:


/**
 * Determines if `input` is a primitive value or not.
 * @param {any} input
 *   The input value to test.
 * @returns {boolean}
 *   Returns `true if `input` is a primitive, otherwise `false` is returned.
 */
function isPrimitive(input) {
  if (input == null) {
    // This is here to correctly handle document.all.
    return input === null || input === undefined;
  }
  const type = typeof input;
  return type !== "object" && type !== "function";
}

In JavaScript, the only primitives that exist are undefined, null, numbers, booleans (true and false), and strings. Therefore, you can use the following code to test out this function:


function test(code) {
  code = "isPrimitive(" + code + ")";
  alert(code + " is " + eval(code));
}

test("undefined"); // isPrimitive(undefined) is true
test("null");  // isPrimitive(null) is true
test("\"primitive\""); // isPrimitive("primitive") is true
test("new String(\"nope\")"); // isPrimitive(new String("nope")) is false
test("3.14"); // isPrimitive(3.14) is true
test("new Number(3.14)"); // isPrimitive(new Number(3.14)) is false
test("true"); // isPrimitive(true) is true
test("new Boolean(9)"); // isPrimitive(new Boolean(9)) is false
test("!9"); // isPrimitive(!9) is true
test("test"); // isPrimitive(test) is false
test("{}"); // isPrimitive({}) is false
test("/^\\d+$/"); // isPrimitive(/\d+/) is false
test("document.all"); // isPrimitive(document.all) is false

After adding this function, I made a few other updates because of its existence, but you will simply have to wait until the next version of jPaq comes out to see what they are. 😉


3 Comments

Josh · March 27, 2014 at 5:26 PM

Corner case:
typeof NaN === 'number'

    Chris West · March 28, 2014 at 1:03 AM

    This is true that in JavaScript NaN is considered a number and thusly a primitive.

Chris West's Blog » JavaScript – isPrimitive() Function · August 2, 2011 at 7:35 PM

[…] See th&#1077 original post: Chris West's Blog » JavaScript – isPrimitive() Function […]

Leave a Reply

Your email address will not be published. Required fields are marked *