LA.NET [EN]

Jan 03

undefined and NaN changes are no longer permitted in ECMAScript 5

Posted in Javascript      Comments Off on undefined and NaN changes are no longer permitted in ECMAScript 5

Happy New Year to everyone! After a small vacation period, I’m back :,,)

Now that the HTML book has gone to revision (more about that in future posts), I guess it’s time to start posting some useful tips in this blog. One of my new year’s resolution is to pay much more attention to JavaScript and that’s why I’ve chose this topic for this year’s first post. If you’ve been reading my blog, you’ll probably recall an old post where I advert for the possibility that anyone can redefine the global undefined and NaN variables. Since this might end up producing some very undesirable effects, I’m really happy to find out that ECMAScript 5 (ie, the JavaScript specification) has forbidden this type of information.

To be more precise, the value properties Nan, Infinity and undefined introduced by the Global Object can’t be changed or configured, nor can they be enumerated in a for–in enumeration. What does that mean? Take a look at the following sample:

<!DOCTYPE html>
<html>
  <head>
    <title>Testing undefined assignment</title>
    <script>
      alert(undefined);
      undefined = "hi";
      alert(undefined);
    </script>
  </head>
  <body></body>
</html>

Now, if you run the previous code in IE9 or in FF 4 (or even in Safari 5), you’ll end up getting the string undefined twice. Notice that you don’t end up getting an exception. You won’t simply be able to change the value…it’s as if you never run the undefined assignment…

Unfortunately, not all browsers are compatible with this new behavior, but I’m thinking that it won’t take long until all of them are compatible with the specs. And that’s it for now. Stay tuned for more  JavaScript posts.