Get Module Version in Node.js

Here’s how to extract the version number from your package.json file. I use this to quickly verify that my current Nodejitsu snapshot is up to date. // Require package.json like a regular module var packageInfo = require('./package.json'); // Do something with the version console.log('VERSION: ' + packageInfo.version); Happy coding.

Array.splice() Unexpected Behavior when Index is Undefined

Today I discovered something you should know about Array.splice() in Javascript. According to this page splice() has a first parameter of index which is supposed to be a number representing the index of the array you wish to splice at. Well, apparently when this index is undefined it acts as though you passed 0 instead. // Create a sample array var array = [ 'a', 'b', 'c' ]; console.log(array); // Remove 1 element from index undefined array.

The NULL Object Hack

Have you ever seen this? foo.bar; /** OUTPUT **/ // // TypeError: Cannot read property 'bar' of null Well, there is an easy solution: if (foo && foo.hasOwnProperty('bar')) { baz = foo.bar; } else { // Do something else } However, this is long and stupid, especially when working with large nested objects. Sometimes if error handling isn’t as important you can get away with this little one-liner.

Dynamically Pluralize Like(s)

I just wanted to share a snippet we use at ForkJoy for pluralizing the various “like” counters on the website. Every menu item has one of these counters and the text can read “no likes”, “1 like”, “2 likes”, etc. Originally we were using an if statement to do this until we realized it can be fit on one line instead. var str; // Prepend with "no" if 0 likes and add // an "s" if number of likes is not 1 str = (item.

ParseInt Fails on Small Numbers

A while ago I was trying to get the floor of a number using parseInt() in a Node.js app. The specific use case was expected to return 0, but a larger integer was returned instead. I opened up the node REPL to test out the behaviour of parseInt() and it turns out that when working with very small or very large numbers parseInt() breaks. Check out the sample below. // Define very small number var small = 5/1000000000; // 5e-9 // parseInt() with radix of 10 var parseIntResult = parseInt(small, 10); // Math.