Thursday, January 17, 2013

Javascript is a Free-For-All....

As part of a boot camp I am teaching this week, we decided to see how much insanity we could inject into Javascript before it would fail.  The group is made up of experienced C# programmers and we decided to experiment with blowing up the sort of structure and type restrictions we have all grown accustomed to in a structured language.  We created the following code block just to see how far we could push the 'undefined ' functionality, along with the variable typing being a basic free-for-all.


var arr = function()
{
  alert(arr['testB']);
}

arr['testA'] = true;
arr['testB'] = false;
arr['testC'] = true;
arr[arr[0]] = arr;

document.write(arr[arr[0]]);
document.write("<br/>");

document.write(arr['testC']);
document.write("<br/>");

document.write(arr[0]);
document.write("<br/>");

arr[arr[0]]();
document.write("<br/>");

document.write("foreach...<br/>");

for (var i in arr)
{
  document.write(arr[i]);
  document.write("<br/>");
}


This is not only viable syntax, but this code will run and output values consistent with the index resolution of the array (when it is an array and not a function, that is).  Interestingly, it appears to be a valid strategy to have an undefined value as a key in a key value pair.  My favorite aspect of this is declaring a function, array and key/value list as a single variable and have it act accordingly depending on how you reference it.  Even when you make one of the values within the key/value array the array itself.

Go home Javascript, you are drunk.

1 comment:

  1. Remarkable things here. I am very glad to see your post.
    Thanks so much and I am taking a look forward to touch you.

    Will you please drop me a e-mail?

    Here is my homepage ... http://evjbs.taurus.uberspace.de/wiki/index.php?title=What_Everyone_Ought_to_Know_About_Web_Hosting

    ReplyDelete