Jia-Luo
Jia-Luo

Reputation: 3293

How do I differentiate between variable types in JavaScript?

In JavaScript, I want to write a function that determines if the two variables passed in are of the same data type, such as string, integer, boolean etc. However, I have no idea as to how to compare the two variables in term of their DATA TYPES instead of the VALUES stored inside the variables.

Thank you in advance =)

Upvotes: 0

Views: 221

Answers (4)

Pointy
Pointy

Reputation: 413712

You can use typeof as suggested, but it's not perfect; an array and a Date instance will both be considered to be of type "object".

Another imperfect way to compare by type is this:

function sameTypes() {
  var tp = null, ts = Object.prototype.toString;
  if (arguments.length === 0) return true; // or false if you prefer
  tp = ts.call(arguments[0]);
  for (var i = 1; i < arguments.length; ++i)
    if (tp !== ts.call(arguments[i])) return false;
  return true;
}

You can pass that function two or more (well one or more I guess) values and it'll return true if the result of calling the "toString" function on the Object prototype is the same for all of them. This one's not perfect because it promotes primitives to objects, so a string constant will seem to have the same type as a String instance.

Upvotes: 3

Adaz
Adaz

Reputation: 1665

Use typeof()

var test = true,
    test2 = "string";

if (typeof(test) === typeof(test2)) {}

Upvotes: 0

Jon
Jon

Reputation: 437336

You can use the typeof operator to find out the data type of a variable. So to test two variables for same type (not necessarily same value), you can use

if(typeof a == typeof b) { /* same type */ }

Upvotes: 1

Uku Loskit
Uku Loskit

Reputation: 42040

You are looking for typeof.

Upvotes: 0

Related Questions