Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unclear Javascript snippet

Tags:

javascript

This Javascript MD5 implementation has me confused.

In the global space, the author declares a var:

var hexcase = 0; 

Later on, the following method appears:

function rstr2hex(input)
{
  try { hexcase } catch(e) { hexcase=0; }
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var output = "";
  var x;
  for(var i = 0; i < input.length; i++)
  {
    x = input.charCodeAt(i);
    output += hex_tab.charAt((x >>> 4) & 0x0F)
           +  hex_tab.charAt( x        & 0x0F);
  }
  return output;
}

The line that I don't understand is:

try { hexcase } catch(e) { hexcase=0; }

What is the author trying to accomplish here?

like image 618
Steve Avatar asked Nov 30 '11 16:11

Steve


1 Answers

He is just making sure hexcase is defined, and if it isn't, he is defining it.

Try putting

try {amIdefined} catch(e) {console.log('was not defined');}

in your console and you'll see...

Note that this is the safest way of making sure the variable is defined. In order to do

hexcase = hexcase || 0;

you need to do var hexcase first, or else you will get an error.

enter image description here

like image 131
hvgotcodes Avatar answered Oct 13 '22 14:10

hvgotcodes