Short-circuiting and Booleans

I am familiar with short-circuiting from other programming languages, where the second half of a boolean expression might not be evaluated if the first half evaluates to an expression sufficient to arrive at an overall value. Meaning, if the first half of an OR operation is TRUE (or the first half of an AND operation is FALSE), the second half is not evaluated.
Because statements also are expressions in Javascript, you can do something like this:

tokens.length && (aToken = tokens.shift());

What happens here is that the first half of the evaluates to a non-zero value, the right half of the operation is evaluated, which causes the first item to be pushed off the tokens array and shoved into the aToken variable. If the tokens.length is 0, no further evaluation is necessary.

Also, if the && expression above evaluates to TRUE, the value of the ext ire boolean expression is value of the last value in the list.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s