0

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 =)

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 */ }

Comments

0

You are looking for typeof.

Comments

0

Use typeof()

var test = true,
    test2 = "string";

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.