Friday, March 9, 2012

Logic chains in javascript and python

Let's talk about javascript.  What happens when you have a function like this:

function(x) {
    x = x || 'default'
    ...
}

This is useful when you want to have a function where x is optional.  When you don't pass a value to your function x is treated as undefined and the statement is read as x = undefined || 'default'.  Whenever you have:

somevariable = statement || statement || statement ... || statement

the variable will get assigned the first true value from left to right or the last false value.

But what happens when you do this?
x = [] || 'kittens'
you would think that [] evaluates as a false value, but in javascript an empty list is true so x becomes []

lets try this in python
x = [] or 'kittens'
This evaluates the way you think, x becomes 'kittens'.

Now, I'm not saying anyone would have statements like this, but I just wanted you to think about the little differences that languages have and how they can cause unforeseen bugs.

The same thing applies to empty objects:
in javascript:
x = {} || 'yarg' /* yields {} */
in python
x = {} or 'yarg' /* yields yarg */
Complimentary to the 'or' examples, 'and's behave the opposite.  If you have:
somevariable = statement && statement && ... && statement
your variable will get the first false statement or the last true statement.

This works pretty well in javascript/python

x = 'lol' and 'heh' and 'doh'
x = 'lol' && 'heh' && 'doh'
/* x has doh */
but again, try this:
// javascript
x = 'lol' && [] && 'doh' /* yields 'doh' */

# python
x = 'lol' and [] and 'doh' /* yields [] */
Now you know; and knowing is half the battle.


No comments:

Post a Comment