Iterate through all powers of 2
for ( var i = 2 ; ; i *= 2 ) { var length = parseInt ( Math . log ( i ) / Math . log ( 10 ) ) + 1 ; if ( length == n ) return parseInt ( Math . log ( i ) / Math . log ( 2 ) ) ; } }