Javascript fuzzy snippet

This Javascript MD5 implementation confused me.

In global space, the author declares var:

var hexcase = 0; 

Next, the following method will appear:

 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 do not understand is:

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

What is the author trying to do here?

+6
source share
5 answers

He just made sure that hexcase defined, and if not, he defines it.

Try to put

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

in the console and you will see ...

Note that this is the safest way to verify that a variable is defined. To make

hexcase = hexcase || 0;

you need to execute var hexcase , otherwise you will get an error message.

enter image description here

+8
source

If the hexcase does not exist, then a ReferenceError thrown and the catch block is executed. If it exists, the catch not executed.

Therefore, it sets hexcase to 0 if it does not exist.

This is a creative way to do it. A more common way is:

 hexcase = window.hexcase || 0; // you have to add window because // otherwise you would still get the error 
+6
source

It looks like hexcase is a global variable that the author is trying to check for. Not sure if the best way to do this though :-)

I would go for:

 if (typeof hexcase === "undefined") { hexcase = 0; } 

Just to make it explicit. You can also use this:

 hexcase = hexcase || 0; 
+2
source

it just checks to see if the hexcase value is defined, and if the default value is not set.

to decide whether the result is capitalized or not ...

+1
source

The try-catch sets the hex code to 0 if it is undefined.

0
source

Source: https://habr.com/ru/post/902761/


All Articles