Categories


Archives


Recent Posts


Categories


How to Identify the Type of a Node.js Variable

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

If you’re creating code for other Node.js developers to use, chances are you’ll need a dash of run-time type checking. While TypeScript can help you with your types on a per-project basis you can’t force third party programmers to use it.

Node’s built-in util module provides a number of useful methods for detecting the type of a variable. Many of the methods for detecting base javascript types (vs Node.js specific types) were deprecated in Node.js 4.0 (release in September of 2015). The methods still exist, but may disappear in a future Node.js release.

Howeverthe deprecation docs include alternatives for identifying these types with native javascript code.

ex.

util.isArray(object)
Added in: v0.6.0    Deprecated since: v4.0.0 
Stability: 0 - Deprecated: Use Array.isArray() instead.

I’m sure there’s tradeoffs to consider for each and everyone of these, but these suggestions provide a good starting point whenever you’re trying to decide which heuristic is the right one for identifying what’s in a particular javascript variable.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 2nd December 2020

email hidden; JavaScript is required