Published 8/28/2020 · 2 min read
Tags: javascript
JavaScript typeof Number
Often you will need to check that you have a number before using it in your JavaScript, here’s how.
typeof 77; // number
77 instanceof Number; // false
Object.prototype.toString.call(77) === "[object Number]";
First you can use the typeof operator on any number either floating point or integer and if it’s a number and either true will be returned if the value is a number.
console.log(typeof 77); // number
OK, job done! There are a couple of other ways to check for numbers though one of which should be avoided.
The Number constructor in JavaScript is used for working with numbers and the Number() function can be used to convert values to numbers. However, calling 77 instanceof of Number; returns false as 77 is a literal value not an instance of the Number constructor.
console.log(77 instanceof Number); // false
Finally, you can use the call method on Object.prototype.toString which will always return [[object Number] if you pass a number into the call method.
Object.prototype.toString.call(77); // '[object Number]'
The above can be used for type checking any primitive and is considered one of the safest ways of type checking although for numbers typeof works just fine.
Object.prototype.toString.call(77); // '[object Number]'
Object.prototype.toString.call("hi"); // '[object String]'
Object.prototype.toString.call(["hi"]); // '[object Array]'
Object.prototype.toString.call({ greet: "hi" }); // '[object Object]' Related Articles
- Testing Svelte 5 Apps: A Practical Guide to Code Structure
How to structure your Svelte code so it's actually testable, with real examples from building a wallet auth system.
- Compressed NFTs: Collections, Verification, and Building a Claim Page
Taking our cNFT minting system to production: creating verified collections, building a web-based claim flow, and preparing for mainnet deployment.
- Building Compressed NFTs on Solana with Generative SVG Art
A practical guide to creating and minting compressed NFTs (cNFTs) on Solana using Metaplex Bubblegum, with animated SVG artwork generated from wallet addresses.