<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>nFriedly Web Dev Tech Blog &#187; optimization</title>
	<atom:link href="http://nfriedly.com/techblog/tag/optimization/feed/" rel="self" type="application/rss+xml" />
	<link>http://nfriedly.com/techblog</link>
	<description>Expert Advice on Website Development, Javascript, Ajax, and Security</description>
	<lastBuildDate>Wed, 01 Feb 2012 22:35:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Advanced Javascript: Logical Operators and truthy / falsy</title>
		<link>http://nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/</link>
		<comments>http://nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 16:54:49 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/?p=46</guid>
		<description><![CDATA[Nearly every website on the internet uses javascript in some form or fashion. Yet very few people, even those who write it and teach it, have a clear understanding of how javascript works! Logical Operators are a core part of the language. We&#8217;re going to look at what logical operators are, what &#8220;truthy&#8221; and &#8220;falsy&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/fleur-design/308974073/"><img class="alignleft" title="speed machine" src="http://farm1.static.flickr.com/104/308974073_9057064747_m.jpg" alt="" width="240" height="160" /></a> Nearly every website on the internet uses javascript in some form or fashion. Yet very few people, even those who write it and teach it, have a clear understanding of how javascript works!</p>
<p>Logical Operators are a core part of the language. We&#8217;re going to look at what logical operators are, what &#8220;truthy&#8221; and &#8220;falsy&#8221; mean, and <strong>how to use this to write cleaner, faster and more optimized javascript</strong>.</p>
<p><span id="more-46"></span></p>
<h2>Javascript Logical Operators</h2>
<p>In traditional programming, operators such as <code>&amp;&amp;</code> and <code>|| </code> returned a boolean value (<code>true</code> or <code>false</code>). This is not the case in javascript. Here it returns the actual <code>object</code>, not a <code>true</code> / <code>false</code>.  To really explain this, I first have to explain what is truthy and what is falsy.</p>
<h3>Truthy or Falsy</h3>
<p>When javascript is expecting a <code>boolean</code> and it&#8217;s given something else, it decides whether the something else is &#8220;truthy&#8221; or &#8220;falsy&#8221;.</p>
<p>An empty string (<code>''</code>), the number <code>0</code>, <code>null</code>, <code>NaN</code>, a boolean <code>FALSE</code>, and <code>undefined</code> variables are all &#8220;falsy&#8221;. Everything else is &#8220;truthy&#8221;.</p>
<pre class="brush: jscript; title: ; notranslate">
var emptyString = &quot;&quot;; // falsy

var nonEmptyString = &quot;this is text&quot;; // truthy

var numberZero = 0; // falsy

var numberOne = 1; // truthy

var emptyArray = []; // truthy, BUT []==false is true. More below.

var emptyObject = {}; // truthy

var notANumber = 5 / &quot;tree&quot;; // falsy
// NaN is a special javascript object for &quot;Not a Number&quot;.

function exampleFunction(){
	alert(&quot;Test&quot;);
}
// examleFunction is truthy
// BUT exampleFunction() is falsy because it has no return (undefined)
</pre>
<p>Gotchas to watch out for: the strings &#8220;0&#8243; and &#8220;false&#8221; are both considered truthy.  You can convert a string to a number with the <code>parseInt()</code> and <code>parseFloat()</code> functions, or by just multiplying it by 1.</p>
<pre class="brush: jscript; title: ; notranslate">
var test = &quot;0&quot;; // this is a string, not a number

(test == false); // returns false, meaning that test is truthy

(test * 1 == false); // returns true, meaning that `test * 1` is falsy
</pre>
<p>As one commenter <a href="#comment-2100">mentioned</a>, arrays are particularly weird. If you just test it for truthyness, an empty array is truthy. HOWEVER, if you compare an empty array to a boolean, it becomes falsy:</p>
<pre class="brush: jscript; title: ; notranslate">
  if([] == false){
    // this code runs
  }

  if( [] ) {
    // this code also runs
  }

  if([] == true){
    // this code doesn't run
  }

  if( ![] ) {
    // this code also doesn't run
  }
</pre>
<p>Another commenter <a href="http://www.nicollet.net/2009/06/the-truth-of-javascript/">pointed out</a> an additional gotcha to watch out for: while javascript evaluates empty arrays as true, PHP evaluates them as false.</p>
<p>PHP also evaluates &#8220;0&#8243; as falsy. (However the string &#8220;false&#8221; is evaluated as truthy by both PHP and javascript.)</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

$emptyArray = array(); // falsy in PHP

$stringZero = &quot;0&quot;; // falsy in PHP

?&gt;
</pre>
<h3>How Logical Operators Work</h3>
<h4>Logical OR, <code>||</code></h4>
<p>The logical OR operator, <code>||</code>,  is very simple after you understand what it is doing. If the first object is truthy, that gets returned. Otherwise, the second object gets returned.</p>
<pre class="brush: jscript; title: ; notranslate">
(&quot;test one&quot; || &quot;test two&quot;); // returns &quot;test one&quot;

(&quot;test one&quot; || &quot;&quot;); // returns &quot;test one&quot;

(0 || &quot;test two&quot;); // returns &quot;Test two&quot;

(0 || false); // returns false
</pre>
<p>Where would you ever use this? The OR operator allows you to easily specify default variables in a function.</p>
<pre class="brush: jscript; title: ; notranslate">
function sayHi(name){

	var name = name || &quot;Dave&quot;;

	alert(&quot;Hi &quot; + name);

}

sayHi(&quot;Nathan&quot;); // alerts &quot;Hi Nathan&quot;;

sayHi(); // alerts &quot;Hi Dave&quot;,
// name is set to null when the function is started
</pre>
<h4>Logical AND, <code>&amp;&amp;</code></h4>
<p>The logical AND operator, <code>&amp;&amp;</code>,  works similarly.  If the first object is falsy, it returns that object. If it is truthy, it returns the second object.</p>
<pre class="brush: jscript; title: ; notranslate">
(&quot;test one&quot; &amp;&amp; &quot;test two&quot;); // returns &quot;test two&quot;

(&quot;test one&quot; &amp;&amp; &quot;&quot;); // returns &quot;&quot;

(0 &amp;&amp; &quot;test two&quot;) // returns 0
</pre>
<p>The logical AND allows you to make one variable dependent on another.</p>
<pre class="brush: jscript; title: ; notranslate">
var checkbox = document.getElementById(&quot;agreeToTerms&quot;);

var name = checkbox.checked &amp;&amp; prompt(&quot;What is your name&quot;);

// name is either their name, or false if they haven't checked the AgreeToTerms checkbox

// IMPORTANT NOTE: Internet Explorer 8 breaks the prompt function.
</pre>
<h4>Logical NOT, <code>!</code></h4>
<p>Unlike <code>&#038;&#038;</code> and <code>||</code>, the <code>!</code> operator DOES turn the value it receives into a boolean. If it receives a truthy value, it returns <code>false</code>, and if it receives a falsy value, it returns <code>true</code>.</p>
<pre class="brush: jscript; title: ; notranslate">
(!&quot;test one&quot; || &quot;test two&quot;); // returns &quot;test two&quot;
// (&quot;test one&quot; gets converted to false and skipped)

(!&quot;test one&quot; &amp;&amp; &quot;test two&quot;); // returns false
// (&quot;test one&quot; gets converted to false and returned)

(!0 || !&quot;test two&quot;); // returns true
// (0 gets converted to true and returned)
</pre>
<p>Another useful way to use the <code>!</code> operator is to use two of them &#8211; this way you always get a <code>true</code> or a <code>false</code> no matter what was given to it.</p>
<pre class="brush: jscript; title: ; notranslate">
(!!&quot;test&quot;); // returns true
//  &quot;test&quot; is converted to false, then that is converted to true

(!!&quot;&quot;); // returns false
// &quot;&quot; is converted to true, and then that true is converted to false

(!!variableThatDoesntExist); // returns false even though you're checking an undefined variable.
</pre>
<h2><a href="http://nfriedly.com/webdev">Javascript Optimization</a></h2>
<p>Need any help <a href="/webdev/javascript">optimizing the Javascript and AJAX on your website</a>? Get in touch with your friendly neighborhood <a href="http://nfriedly.com/webdev">javascript expert</a> for ideas on how to optimize your site and a free quote.</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

