How to get the object type
Categories:
Mastering Type Identification in Google Apps Script and JavaScript

Learn various techniques to accurately determine the type of an object or variable in JavaScript and Google Apps Script, avoiding common pitfalls and TypeErrors.
Understanding the type of a variable or object is fundamental in JavaScript and Google Apps Script development. Incorrectly assuming a type can lead to unexpected behavior, runtime errors (like TypeError
), and difficult-to-debug issues. This article explores robust methods for type checking, from basic primitives to complex objects and host-specific types found in Google Apps Script.
The typeof
Operator: Basic Type Checking
The typeof
operator is the most straightforward way to check the type of a variable. It returns a string indicating the type of its operand. While useful for primitive types, it has limitations, especially when dealing with objects and null
.
console.log(typeof 42); // "number"
console.log(typeof 'hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol('id'));// "symbol"
console.log(typeof 123n); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof null); // "object" (a long-standing bug in JavaScript)
console.log(typeof function(){});// "function"
Examples of typeof
operator usage.
typeof null
quirk, which returns 'object'
. This is a historical bug in JavaScript and can lead to incorrect assumptions if not handled explicitly.Advanced Type Checking with Object.prototype.toString
For more precise type identification, especially for distinguishing between different types of objects (e.g., arrays, dates, regular expressions), Object.prototype.toString.call()
is a reliable method. It returns a string in the format "[object Type]"
, where Type
is the internal [[Class]]
property of the object.
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
console.log(getType({})); // "Object"
console.log(getType([])); // "Array"
console.log(getType(new Date())); // "Date"
console.log(getType(/regex/)); // "RegExp"
console.log(getType(null)); // "Null"
console.log(getType(undefined)); // "Undefined"
console.log(getType(42)); // "Number"
console.log(getType('hello')); // "String"
console.log(getType(new String('hi'))); // "String"
// Google Apps Script specific types
// var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// console.log(getType(sheet)); // "Sheet" (or similar, depending on host object)
// var range = sheet.getRange('A1');
// console.log(getType(range)); // "Range"
Using Object.prototype.toString.call()
for accurate type identification.
flowchart TD A[Start: Variable `myVar`] B{Is `myVar` === null?} C{Is `typeof myVar` === 'undefined'?} D{Is `typeof myVar` === 'object'?} E{`Object.prototype.toString.call(myVar)`} F{Return "Null"} G{Return "Undefined"} H{Return `typeof myVar` (for primitives/functions)} I{Extract Type from `[object Type]`} J[End: Identified Type] A --> B B -- Yes --> F B -- No --> C C -- Yes --> G C -- No --> D D -- Yes --> E D -- No --> H E --> I F --> J G --> J H --> J I --> J
Decision flow for comprehensive type identification.
Checking for Specific Object Instances with instanceof
The instanceof
operator checks if an object is an instance of a particular class or constructor function. It's useful for custom objects and built-in types that are instantiated with new
.
class MyCustomClass {}
const myInstance = new MyCustomClass();
const myDate = new Date();
const myArray = [];
console.log(myInstance instanceof MyCustomClass); // true
console.log(myDate instanceof Date); // true
console.log(myArray instanceof Array); // true
console.log(myArray instanceof Object); // true (due to prototype chain)
console.log('hello' instanceof String); // false (primitive string)
console.log(new String('hello') instanceof String); // true (String object)
Using instanceof
for checking object inheritance.
instanceof
operator works across different JavaScript execution contexts (e.g., iframes) only if the constructor function is the same. For Google Apps Script, it's generally reliable for host objects within the same script execution.Google Apps Script Host Objects and TypeErrors
Google Apps Script introduces many host objects (e.g., Sheet
, Range
, Folder
, Document
). While Object.prototype.toString.call()
often works well for these, sometimes direct property checks or specific API methods are necessary, especially when dealing with objects that might be null
or undefined
due to failed lookups (e.g., SpreadsheetApp.getActiveSpreadsheet().getSheetByName('NonExistentSheet')
returns null
).
TypeError
is a common error when you try to perform an operation on a value that is not of the expected type. For instance, calling a method on null
or undefined
will result in a TypeError
.
function processSheet(sheetName) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
if (sheet === null) { // Explicitly check for null
console.error(`Sheet '${sheetName}' not found.`);
return;
}
// Now it's safe to call methods on 'sheet'
console.log(`Sheet name: ${sheet.getName()}`);
console.log(`Sheet type (using toString): ${Object.prototype.toString.call(sheet).slice(8, -1)}`);
// Example of a potential TypeError if not checked
// const nonExistentSheet = ss.getSheetByName('DefinitelyNotHere');
// nonExistentSheet.getName(); // This would throw a TypeError: Cannot read property 'getName' of null
}
// processSheet('Sheet1');
// processSheet('NonExistentSheet');
Handling Google Apps Script host objects and preventing TypeError
.
null
or undefined
when retrieving objects from Google Apps Script services, as many get
methods return these values if the requested item doesn't exist, leading to TypeError
if you attempt to use them.