Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript: isPrimitive
var isPrimitive = function(val) {
return val !== function() { return this; }.call(val);
};
'use strict';
var isPrimitive = function(val) {
return val == null || /^[sbn]/.test(typeof val);
};
var assert = require('assert');
assert.ok(isPrimitive(null));
assert.ok(isPrimitive(undefined));
assert.ok(isPrimitive(1));
assert.ok(isPrimitive('foo'));
assert.ok(isPrimitive(true));
assert.ok(isPrimitive(false));
assert.ok(isPrimitive(NaN));
assert.ok(isPrimitive(Infinity));
assert.equal(isPrimitive({}), false);
assert.equal(isPrimitive([]), false);
assert.equal(isPrimitive(/./), false);
assert.equal(isPrimitive(global), false);
assert.equal(isPrimitive(function() {}), false);
assert.equal(isPrimitive(new function() {}), false);
assert.equal(isPrimitive(new Number), false);
assert.equal(isPrimitive(new String), false);
assert.equal(isPrimitive(new Boolean), false);
assert.equal(isPrimitive(new Date), false);
assert.equal(isPrimitive(new Error), false);
assert.equal(isPrimitive(Object.create(null)), false);
3
@patik

This comment has been minimized.

Copy link

commented Sep 18, 2012

Regexp?

@cowboy

This comment has been minimized.

Copy link
Owner Author

commented Sep 18, 2012

RegExp is represented via /./

@AutoSponge

This comment has been minimized.

Copy link

commented Sep 18, 2012

function isPrimitive(val) {
return val !== Object(val);
}

function isPrimitive(val) {
return !Object.prototype.isPrototypeOf(val);
}

@bobmyers

This comment has been minimized.

Copy link

commented Nov 24, 2014

@AutoSponge, your second version of isPrimitive fails on objects created via Object.create(null, ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.