KishCom

Developer. Gamer. Yo-Yo Thrower.

More JavaScript Wonders

Another couple JavaScript oddities I’ve run into recently.
The first one is to do with function expressions vs. function blocks.

//A function in a block
var aNumber = getNumber(); //Returns 42 as you might expect
function getNumber() { return 42; }

Now a slight variation of the same script:

var aNumber = getNumber(); //Error: getNumber is undefined
var getNumber = function() { return 42; }

Why?! It’s easy: function expressions are evaluated at runtime. Function ‘blocks’ are parsed at runtime. Neat little gotcha right?

The next one was brought to my attention from one of my co-workers who was refreshing his JavaScript knowledge:

var aNumber = 42;
var aString = "42";

var result = aString + aNumber; // result is now "4242" - String is automatically concatenated
var result = aString - aNumber; // result is now 0 - String is automatically parseInt() and evaluated

This is just JavaScript being clever – it knows you might want to join two strings, but no such ‘logical’ operation exists if you’re using a minus sign. A very interesting different result based on a mere plus or minus symbol. Always use parseInt and mind your NaNers. 😉

Back to KishCom.com
KishCom.Com

Table of Contents