I was writing a simple recursive function in JavaScript and encountered some really weird behavior. At first I thought it's bug in a browser, but I tried it in FireFox, Chrome and IE9 and they all behave exactly the same way.
The HTML file below runs a simple JS function on page load. The function is recursive (calling itself exactly once). Essentially the function creates a new Array object and returns it. The weird thing is that after the function calls itself recursively, x and y reference to the same object, which as far as I understand it should not happen. Also if you uncomment the last line before return x, the alert "x == y" alert is not shown.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>JavaScript weirdness...</title>
<script type="text/javascript" language="javascript">
function RecursiveF(n) {
x = [ n ];
if (n > 0) {
y = RecursiveF(n - 1);
if (x == y)
alert('x == y');
}
//if (n == 0) return [ n ];
return x;
}
</script>
</head><body onload="javascript:RecursiveF(1);"></body></html>
Any hints to why "x == y" alert appears in this page?