Here We print the result of typeof to the page with console.log. We see the lowercase type strings.
Info We use an if, else chain to test the result of typeof. In this way we can test the types of array elements.
// Create test array.
var values = ["cat", 100, function(){}];
// Write the result of typeof.
for (var i = 0; i < values.length; i++) {
console.log("TYPEOF RESULT: " + typeof values[i]);
}
// Test the elements with typeof.
for (var i = 0; i < values.length; i++) {
if (typeof values[i] === "string") {
console.log("FOUND string");
}
else if (typeof values[i] === "number") {
console.log("FOUND number");
}
else if (typeof values[i] === "function") {
console.log("FOUND function");
}
}TYPEOF RESULT: string
TYPEOF RESULT: number
TYPEOF RESULT: function
FOUND string
FOUND number
FOUND function
Arrays. For arrays, we cannot use a "typeof array" expression. We must use the Array.isArray method. We can use isArray on literal arrays and arrays created with the Array constructor.
var test = [1, 2, 3];
// See if the value is an array.
if (Array.isArray(test)) {
console.log("ISARRAY");
}
if (typeof test === "array") {
// This does not work.
console.log("ERROR");
}
var emptyArray = Array(100);
// We can also test an array made with the Array constructor.
if (Array.isArray(emptyArray)) {
console.log("ISARRAY");
}ISARRAY
ISARRAY
Summary. With the typeof operator we get a string that tells us an object's type. The typeof operator appears to perform fast in Node.js—about as fast as a null check.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).