An instance of the typeof operator usage in JavaScript

  • 2020-03-30 02:34:15
  • OfStack

Using the typeof operator on a value may return one of the following strings:
"Undefined" -- if the value is undefined
"Boolean" -- if the value is a Boolean
"String" -- if the value is a string
"Number" -- if the value is a number
"Object" -- if this is an object or null
"Function" -- if this value is a function

The return values of the commonly used typeof operators include number, string, Boolean, undefined, object, and function. Such as:


var n;
console.log(typeof n); // "undefined"

n = 1;
console.log(typeof n); // "number"

n = "1";
console.log(typeof n); // "string"

n = false;
console.log(typeof n); // "boolean"

n = { name: "obj" };
console.log(typeof n); // "object"

n = new Number(5);
console.log(typeof n); // "object"

n = function() { return; };
console.log(typeof n); // "function"

These examples show that the operands of the typeof operator can be either a variable (message) or a literal value. Note that typeof is an operator, not a function, so the parentheses in the example are not required (although they can be used).


From the above example, we found that with the Number () to create the Number will also be a typeof judged object and returns a value of "object", this is because the constructor returns are objects, so if we want to distinguish between digital objects (Number), a String object (String), object Array (Array), Function objects, Date (Date), the Boolean object (Boolean) and Error object (Error) and so on the built-in JavaScript object, how to do? Here you can call the toString method of the object, such as:


var n, res;

n = new Number(66);
res = Object.prototype.toString.call(n);
console.log(res); // "[object Number]"

n = new String("string");
res = Object.prototype.toString.call(n);
console.log(res); // "[object String]"

n = [];
res = Object.prototype.toString.call(n);
console.log(res); // "[object Array]"

// ...


Related articles: