Tuesday, June 18, 2013

_.isUndefined in underscore.js

This will give an alert saying "foo is undefined" followed by a second alert saying "foo is for real" immediately after:

<html>
   <head>
      <script type="text/javascript" src="underscore.js"></script>
      <script type="text/javascript">
         var foo;
         checkFoo();
         foo = "foo";
         checkFoo();
         function checkFoo() {
            if (!_.isUndefined(foo)) {
               alert('foo is for real');
            } else {
               alert('foo is undefined');
            }
         }
      </script>
   </head>
   <body />
</html>

 
 

It more or less behaves like so:

<html>
   <head>
      <script type="text/javascript">
         var foo;
         checkFoo();
         foo = "foo";
         checkFoo();
         function checkFoo() {
            if (foo) {
               alert('foo is for real');
            } else {
               alert('foo is undefined');
            }
         }
      </script>
   </head>
   <body />
</html>

 
 

I suppose in the second scenario foo could vary its behavior from the first scenario's circumstance by being set to false.

No comments:

Post a Comment