- JavaScript Data Type Check Cheatsheet
- Classic JavaScript Data Type Checks
- Check if JavaScript variable contains an object
- Check if a value is a string in JavaScript
- Check if a value is a JavaScript Number/Integer
- Checking that a Number is not NaN (Not A Number)
- Check if a JavaScript variable contains an Integer
- Check if a JavaScript variable contains a useable Number value
- Check if a value is a boolean
- Check if a variable contains an Array
- Check if an object is an instance of a specific class/constructor function
- Check if an object is an Error
- Check for a valid JavaScript Date string (parseable date-string)
- Check for a valid JavaScript Date
- Check if a JavaScript variable is a Promise
- Check if a JavaScript variable is a function
- Debugging JavaScript Data Type Issues
- Figuring out if something is a Promise
- A promise that’s supposed to return a list
- A promise that’s supposed to return an object
- Debugging Array vs Array-like
- Source Materials — Further Reading
- Get The Jest Handbook (100 pages)
- Hugo Di Francesco
- Get The Jest Handbook (100 pages)
- #javascript
- Add Search to a Hugo site with Lunr.js and Node.js
- Tailwind CSS 1.x impressions, development and production setup for static sites with Tailwind CLI and PurgeCSS CLI
JavaScript Data Type Check Cheatsheet
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions.
MDN Web Docs — javascript
Detailed in this post are common JavaScript data type checks, pitfalls and idiomatic workarounds.
Classic JavaScript Data Type Checks
Here’s a collection of the most common data type checks in JavaScript. Whether you want to check if a variable contains a Date, a Promise, a plain old JavaScript object or an Array, it’s all here.
Everything from primitive types like number, boolean, string to detecting functions.
Check if JavaScript variable contains an object
typeof does output ‘object’ for objects.
It also does so for null and Arrays.
What’s more, much like in the case of Arrays, if there is inter-frame communication, it tends to share objects and arrays (see JavaScript array type check — “is array” vs object in-depth). Therefore, checking whether something is a simple object vs an instance of a class is difficult.
In JavaScript you’ll notice that everything is an Object, and when you try to access a property that doesn’t exist, it’ll fail quietly (ie. return undefined ):
In idiomatic JavaScript code, we leverage this property to be just defensive enough, for example if we expect an object that has a growl method, but something else might be passed in:
The moral of the story is: don’t check that something is an object, check that it has the properties you need (that’s what’s called duck typing).
Check if a value is a string in JavaScript
For strings, we can use a typeof check.
Much the same as for object checks, JavaScript won’t fail loudly when you try to use something as a string that isn’t a string, it will tend to just coerce it or call .toString on it.
This works with dates, number. For arrays and other objects that don’t directly implement a toString method, I would suggest using JSON.stringify.
Check if a value is a JavaScript Number/Integer
JavaScript Numbers are a bag of fun. They’ve got a similar gotcha to object checks, that’s the NaN (Not a Number) value. NaN usually is the output of trying to do arithmetic where one of the operands is not a Number.
The quirks of NaN is that it’s not equal to itself, and it’s actually a Number, just like Infinity and — Infinity
Checking that a Number is not NaN (Not A Number)
One NaN check would just be:
The recommended approach is the following, there’s a built-in Number.isNaN function:
The difference between Number.isNaN and the isNaN global is that Number.isNaN checks that the value passed in is a Number and it is NaN .
The older global isNaN function just goes for the literal check that something is not a number.
Check if a JavaScript variable contains an Integer
To check that JavaScript variable (or value) is an integer, we can use Number.isInteger :
Check if a JavaScript variable contains a useable Number value
To check that we’ve got a useable input value, we should check that the type is number and that the value is not NaN:
Check if a value is a boolean
As with JavaScript string and number data types, in JavaScript the pattern is to assume something is a boolean (or cast it to boolean) rather than checking that it’s a boolean. That’s because in JavaScript we can use logical operators with non boolean values due to the loose typing, this is usually explained through the concept of “truthiness” and “falsiness”.
When JavaScript is expecting a boolean and it is given one of the values below, it will always evaluate to “falsy”
MDN Web Docs — Falsy
The values in question (falsy values) are: false , 0 , » (or other empty string), null and undefined . Any other value will be evaluated to true.
There are some cases where false means something other than undefined , in that case, it’s possible to check that a value is falsy and a boolean by using the typeof :
Check if a variable contains an Array
To check if a JavaScript variable is an Array, there’s a built-in Array.isArray .
The fun gotcha with JavaScript Arrays is that they’re just objects.
A way to duck-type an Array is to use existence of a .length property. However this can be pretty weak since there’s nothing enforcing that Arrays should be the only type to have a .length property. The pattern tends to look like so:
Now this code doesn’t actually check that maybeArray is an Array. It sort of does that but in the same line of code ie. !maybeArray.length , it also states that maybeArray must have a non-falsy length, ie. in the case where it is in fact an Array, it shoul also not have length 0 (must not be empty).
It’s trivial to trick the above and make it crash on .map with for example using the following data: < length: 'aaaa' >. That’s not the point, if consumers of this function are trusted, this kind of check can be fine.
Using Array.isArray however works as follows:
For a closer look at the internals of how we check for Arrays, see JavaScript array type check — “is array” vs object in-depth. The big gotcha with built-in JavaScript data types like Array, Object and Date in JavaScript is that communicating between frames means the constructors and therefore instanceof checks don’t work.
Check if an object is an instance of a specific class/constructor function
Say you’ve got a set variable and you want to check that it’s a React Component, you can do:
This also works with constructor functions:
Another interesting thing is it works all the way up the prototype chain/class hierarchy:
Check if an object is an Error
Error is just a constructor/class. So in the same way we could check for React.Component or Dog class:
Check for a valid JavaScript Date string (parseable date-string)
The above function doesn’t actually check whether something is a valid string but whether it’s convertible to a valid date.
For most intents and purposes, it will catch dodgy date strings, and has the benefit of not being unreadable at the cost of allow number timestamps to be passed in. A more apt name might be isConvertibleToDate . Disallowing numbers would just be a case of adding a typeof maybeDateString === ‘string’ .
Check for a valid JavaScript Date
To check whether or not something is a valid, we’ll just take the same approach as checking whether it’s convertible to a date
You could also apply the instanceof approch:
This has some cross-frame issues and you never know when someone might mess with the global Date to replace it with their own custom, non-standard version.
Check if a JavaScript variable is a Promise
Promise checks are done using instanceof with all the usual cross-frame or custom implementation caveats:
With Promises there’s also the issue for then-ables. Which for most intents and purposes may as well be Promises but which won’t pass our above check.
In async/await-enabled environments, you’ll also note that await -ing a function that doesn’t return a Promise doesn’t cause any unintended side-effects, the return value of the function (even if it’s not an async function), can be stored the same way as you would if you hadn’t await -ed.
Check if a JavaScript variable is a function
As mentioned on the MDN Web Docs JavaScript is a “programming language with first-class functions”. First-class functions, just means functions are treated like any other variable.
Refer to the object example to see how an idiomatic “run this function if it exists” would look.
Debugging JavaScript Data Type Issues
What does each of the following look like when it’s console.log -ed?
One of the big issues is that console.log tends to stringify whatever object it’s passed using its .toString() method. A lot of the time, a combination of pattern matching, logging out typeof and logging out a JSON.stringify -ed version of the object gives good results.
Figuring out if something is a Promise
Forgot to await a function that returns a Promise (including an async function).
You usually want to do something with the output of the Promise:
A promise that’s supposed to return a list
A promise that’s supposed to return an object
Debugging Array vs Array-like
There are a few Array-like objects in JavaScript for example arguments , NodeList s (output of document.querySelectorAll ).
The first thing to do is to just log them out:
Here is the old-school method of converting them to regular Array -s (which means you can use Array.forEach/.map etc.):
The ES6 approach would look something closer to this, they take advantage of array spread syntax and rest parameters syntax respectively.
A more conservative approach could leverage Array.from (see Array from MDN Web Docs):
Source Materials — Further Reading
While creating this JavaScript Data Type Check guide, I took inspiration from some of the top relevant posts:
Get The Jest Handbook (100 pages)
Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.
Join 1000s of developers learning about Enterprise-grade Node.js & JavaScript
Hugo Di Francesco
Co-author of «Professional JavaScript», «Front-End Development Projects with Vue.js» with Packt, «The Jest Handbook» (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.
Get The Jest Handbook (100 pages)
Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.
#javascript
Add Search to a Hugo site with Lunr.js and Node.js
Hugo “The world’s fastest framework for building websites” is a great option for JAMStack (JavaScript, APIs, prebuild Markup) sites. Lunr.js is “A bit like Solr, but much smaller and not as bright”, it’s a pure JavaScript implementation of a Solr-like search engine. One of the only things it doesn’t provide out of the box is Search. It does give you a few options to integrate at “Search for your Hugo Website”. None were plug and play so I wrote my own simple solution using Lunr.js, a small Node.js script and a few lines of client-side HTML/JavaScript code. This is a great example of a benefit of Node.js: it’s a breeze to integrate a pure JavaScript library and pre-compute the search index. You can see Search in action at codewithhugo.com/search/?q=lunrjs. Find the full gist at gist.github.com/HugoDF .
Hugo Di Francesco
Tailwind CSS 1.x impressions, development and production setup for static sites with Tailwind CLI and PurgeCSS CLI
How to set Tailwind CSS up with a static site hosted on Netlify See the full starter repository at github.com/HugoDF/netlify-lambda-tailwind-static-starter Tailwind CSS is “a utility-first CSS framework for rapidly building custom designs”. I’ll be walking through my first impressions of it as well as how to leverage its CLI (and the PurgeCSS CLI) to add it to any project without a build process (eg. Webpack, Gulp). .
Hugo Di Francesco