Javascript truthy and falsy , Javascript logic operators || and &&

In JavaScript, logical operators are used for boolean logic where a boolean value may be returned depending on the outcome of an expression. With the || (OR) operator, since values don't need to be explicitly true or false (they can be truthy or falsy), the operator can return non-boolean results when evaluated.

Introduction

To understand the || operator, let's first look at a fairly basic example. The logical OR operator may be used to provide a default value for a defined variable as follows:

  1. var bar = false,  
  2.      foobar = 5,  
  3.      foo = bar || foobar; // foo = 5  

In this case, foo will only be assigned the value of foobar if bar is considered falsy. A falsy value could be considered being equal to 0falseundefinednullNaN or empty (e.g "").

This pattern might look familiar as if you've written jQuery plugins before or used$.extend(), you'll see it implemented when checking for an options object to either be specified or set to an explicit default value:

  1. function( options ) {  
  2.     options = $.extend({}, defaults, options || {});  
  3. }  

Some developers also like using the || operator to set explicit null values when handling falsy values in an application. This helps ensure that values are intentionally nullified:

  1. var foo = bar || null;  

Commonly, you're unlikely to want null values but when you do, there's a certain comfort in not having to wonder if it's a desired value or if it indeed should be a nullified property or variable.

You may also see developers opting for this approach to default-namespacing, where rather than opting for a two-line statement consisting of namespace = namespace || {} and populating the object later, this is all done at once as follows:

  1. var namespace = namespace || {  
  2.     utils:{},  
  3.     core:{}  
  4. };  

Behind The Scenes

Now, JavaScript variables aren't typed, so a variable may be assigned a value (e.g. a number), despite being assigned through boolean operators:

  1. console.log(null || NaN || undefined || false || 0 || 10);  
  2. // outputs: 10  

What's happening here isn't quite magic—the expression is simply being lazily evaluated. The interpreter checks the value of the first part of the statement, null, establishes that it's falsy and continues moving forward until a falsy value isn't found (or if no truthy value is found, returning the last value). It's a neat trick that works in dynamic languages beyond just JavaScript, but won't work in static languages, where a type error will be thrown if you try the above.

If you're interesting in reading up more about the evaluation technique used in this example, check out short-circuit evaluation.

So, where is any of this useful? The OR operator can be applied to functions where we wish to provide a default value (as we've seen earlier) if falsy-ness is incurred as follows:

  1. function foo( a, b ){  
  2.         a = a || 5;  
  3.         b = b || 6;  
  4.         console.log( 'Values:' + a + ',' +b );  
  5. }  

Although, you're more likely to see a ternary to solve this problem in the wild, or perhaps something similar to this:

  1. if(a && a === 5){  
  2.         // do something  
  3. }else{  
  4.         // do something else  
  5. }  

You may be wondering why. In my opinion it comes down to two things:

Readability: Some developers feel that if/else is easier to read and it can certainly save time when you don't have to evaluate the expression in your mind while looking through code. I would argue that we still have to do the same with if/else, but it comes down to a matter of preference at the end of the day.

Performance: The developers I've discussed the OR operator with have had a perception that if statements had to be more performant than ||, however I believed they had to be at least equivalent performance-wise.

Performance Testing

With the aid of jsPerf, we can test out one example of OR vs IF to find out how they compare:

Performance testing: OR vs IF

  1. var caseTrue = false;  
  2. function sum(){  
  3.         return 100 + 10;  
  4. }  
  5. // test 1  
  6. caseTrue || sum();  
  7. // test 2  
  8. if(!caseTrue){  
  9.         sum();  
  10. }  

 

 

More Tricks

Now that we've looked at performance testing, there are a few other tricks that the logical operator can be used for. In the following example if the expression on the left evaluates to true, a positive equality message is logged whilst evaluating to false has the opposite effect.

  1. var bar = 5;  
  2. bar == 5 && console.log('bar equals 5');  
  3. // outputs: bar equals 5  
  4. bar == 8 || console.log('bar does not equal 8');  
  5. // outputs: bar does not equal 8  

And just for the curious:

  1. bar == 5 || console.log('bar equals 5');  
  2. // evaluates to true  
  3. bar == 8 && console.log('bar does not equals 8');  
  4. // evaluates to false  

The logical OR operator can also however be used in a number of other places:

  1. ('foo' || 'bar'); // returns foo  

Although a specific falsy value hasn't been assigned to either side above, the first object is considered truthy in this case, which is why foo is returned. The second object would be returned if the first was falsy.

Extending the 'default value' concept slightly, it's possible to define functions that either execute specific methods defined within a namespace, or define those methods if they don't exist. This can be done a number of different ways (with optional type-checking), but a basic example could look like:

  1. function helloWorld( fn ){  
  2.     (fn.method = fn.method || function() {  
  3.         console.log('foo');  
  4.     })();  
  5. }  
  6. helloWorld({}); // outputs: foo  
  7. //passing in an object with a method  
  8. helloworld({  
  9.         method:function(){  
  10.                 console.log('boo');  
  11.         }  
  12. }); //outputs boo  

The || operator could also be used in combination with a ternary to support:

  • Querying the DOM for an element if a reference we expect to be cached is falsy/undefined
  • Dynamically creating the element if the result of querying the DOM is that the element didn't exist and thus returned an empty result.
  1. // bar, either undefined or a cached selection of $('#bar')  
  2. // var bar = $('#bar');  
  3. var bar;  
  4. // if bar isn't undefined/falsey, use bar, otherwise query the  
  5. // DOM for the div 'bar' so we can cache it in 'foo' if  
  6. // bar has a valid length (i.e isn't an empty collection)  
  7. // if bar doesn't exist in the global scope and isn't currently  
  8. // in the DOM, we'll dynamically create a div and set it's ID to  
  9. // 'bar' instead.  
  10. var foo = bar = bar && bar.length && bar ||  
  11.     (bar = $('#bar')).length ? bar :  
  12.     $('<div />', { id: 'bar' });  
  13. console.log(foo, bar);  

 

You can try out the above code sample here:http://jsfiddle.net/dY5W9/6/

The above approach to solving this problem should typically not be used in production environments and is only shown for demonstration purposes. There are far simpler (and more readable) ways this problem can be solved.

Finally, here are some further experiments using the OR operator, just in case you're interested in how truthy/falsy/other values are evaluated:

  1. true || true       // returns true  
  2. false || true      // returns true  
  3. true || false      // returns true  
  4. false || (5 === 6)  // returns false  
  5. "foo" || "bar"     // returns foo  
  6. false || "bar"     // returns bar  
  7. "foo" || false     // returns foo  
  8. (0 || 'bar'); // returns bar  
  9. (false || true || false || false); // true  
  10. (false || false || true); // true  

Wrapping Up

That's it! Whilst || has many potential uses, always remember to factor in readability of your code when opting to use it. If you have any other gotchas, corrections or comments to share, feel free to leave them below and we'll get back to you. Happy coding.

 

 

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’re going to look at what logical operators are, what “truthy” and “falsy” mean, and how to use this to write cleaner, faster and more optimized javascript.

 

Javascript Logical Operators

In traditional programming, operators such as && and || returned a boolean value (true or false). This is not the case in javascript. Here it returns the actual object, not a true / false.  To really explain this, I first have to explain what is truthy and what is falsy.

Truthy or Falsy

When javascript is expecting a boolean and it’s given something else, it decides whether the something else is “truthy” or “falsy”.

An empty string (''), the number 0nullNaN, a boolean FALSE, and undefined variables are all “falsy”. Everything else is “truthy”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var emptyString = "" ; // falsy
 
var nonEmptyString = "this is text" ; // truthy
 
var numberZero = 0; // falsy
 
var numberOne = 1; // truthy
 
var emptyArray = []; // truthy, BUT []==false is true. More below.
 
var emptyObject = {}; // truthy
 
var notANumber = 5 / "tree" ; // falsy
// NaN is a special javascript object for "Not a Number".
 
function exampleFunction(){
     alert( "Test" );
}
// examleFunction is truthy
// BUT exampleFunction() is falsy because it has no return (undefined)

Gotchas to watch out for: the strings “0″ and “false” are both considered truthy.  You can convert a string to a number with the parseInt() and parseFloat() functions, or by just multiplying it by 1.

1
2
3
4
5
var test = "0" ; // 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

As one commenter mentioned, 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if ([] == false ){
   // this code runs
}
 
if ( [] ) {
   // this code also runs
}
 
if ([] == true ){
   // this code doesn't run
}
 
if ( ![] ) {
   // this code also doesn't run
}

Another commenter pointed out an additional gotcha to watch out for: while javascript evaluates empty arrays as true, PHP evaluates them as false.

PHP also evaluates “0″ as falsy. (However the string “false” is evaluated as truthy by both PHP and javascript.)

1
2
3
4
5
6
7
<?php
 
$emptyArray = array (); // falsy in PHP
 
$stringZero = "0" ; // falsy in PHP
 
?>

How Logical Operators Work

Logical OR, ||

The logical OR operator, ||,  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.

1
2
3
4
5
6
7
( "test one" || "test two" ); // returns "test one"
 
( "test one" || "" ); // returns "test one"
 
(0 || "test two" ); // returns "Test two"
 
(0 || false ); // returns false

Where would you ever use this? The OR operator allows you to easily specify default variables in a function.

1
2
3
4
5
6
7
8
9
10
11
12
function sayHi(name){
 
     var name = name || "Dave" ;
 
     alert( "Hi " + name);
 
}
 
sayHi( "Nathan" ); // alerts "Hi Nathan";
 
sayHi(); // alerts "Hi Dave",
// name is set to null when the function is started

Logical AND, &&

The logical AND operator, &&,  works similarly.  If the first object is falsy, it returns that object. If it is truthy, it returns the second object.

1
2
3
4
5
( "test one" && "test two" ); // returns "test two"
 
( "test one" && "" ); // returns ""
 
(0 && "test two" ) // returns 0

The logical AND allows you to make one variable dependent on another.

1
2
3
4
5
6
7
var checkbox = document.getElementById( "agreeToTerms" );
 
var name = checkbox.checked && prompt( "What is your name" );
 
// name is either their name, or false if they haven't checked the AgreeToTerms checkbox
 
// IMPORTANT NOTE: Internet Explorer 8 breaks the prompt function.

Logical NOT, !

Unlike && and ||, the ! operator DOES turn the value it receives into a boolean. If it receives a truthy value, it returns false, and if it receives a falsy value, it returns true.

1
2
3
4
5
6
7
8
(! "test one" || "test two" ); // returns "test two"
// ("test one" gets converted to false and skipped)
 
(! "test one" && "test two" ); // returns false
// ("test one" gets converted to false and returned)
 
(!0 || ! "test two" ); // returns true
// (0 gets converted to true and returned)

Another useful way to use the ! operator is to use two of them – this way you always get a true or afalse no matter what was given to it.

1
2
3
4
5
6
7
(!! "test" ); // returns true
//  "test" is converted to false, then that is converted to true
 
(!! "" ); // returns false
// "" is converted to true, and then that true is converted to false
 
(!!variableThatDoesntExist); // returns false even though you're checking an undefined variable.

 

 

see also : 

http://addyosmani.com/blog/exploring-javascripts-logical-or-operator/

http://nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/

 

你可能感兴趣的:(JavaScript)