C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Loop 1: We print the result of typeof to the page with console.log. We see the lowercase type strings.
Loop 2: We use an if, else chain to test the result of typeof. In this way we can test the types of array elements.
JavaScript program that uses typeof
// 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");
}
}
Output
TYPEOF RESULT: string
TYPEOF RESULT: number
TYPEOF RESULT: function
FOUND string
FOUND number
FOUND function
JavaScript program that tests for array type
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");
}
Output
ISARRAY
ISARRAY
Version 1: The typeof operator is used on each string. The result variable is incremented on each element in the array.
Version 2: This version of the code just tests to see if the string is not undefined in the array.
Result: Based on the benchmark (done in 2019), typeof is a good choice for JavaScript programs—it executes fast.
JavaScript program that benchmarks typeof
var result = 0;
var values = ["cat", "bird", "frog"];
var x1 = performance.now();
// Version 1: use typeof.
for (var i = 0; i < 1000000; i++) {
for (var x = 0; x < values.length; x++) {
if (typeof values[x] === "string") {
result++;
}
}
}
var x2 = performance.now();
// Version 2: test against undefined.
for (var i = 0; i < 1000000; i++) {
for (var x = 0; x < values.length; x++) {
if (values[x]) {
result++;
}
}
}
var x3 = performance.now();
// Results.
console.log("TIME 1: " + (x2 - x1));
console.log("TIME 2: " + (x3 - x2));
Output
TIME 1 (2019): 10.039
TIME 2: 11.939