Posted By

noah on 06/23/08


basic variable conditional operators logic and boolean easy tips crockford refactoring 2008 logical assignment

Versions (?)

Who likes this?

2 people have marked this snippet as a favorite


Conditionally assign a value to a variable

 / Published in: JavaScript


To assign a value to a variable only if some expression evaluates to true, I would usually do this:

var foo;
  if (condition){
    foo = "success";

This is Douglas Crockford's idiom and it shortens the above from 4 lines to 1.

I have understood for a while that (expr1 && expr2) evaluates to truth only if both conditions are true. What I did not get before Crockford pointed it out in his book, was that && doesn't simply return a boolean value -- it returns the result of the last expression that was evaluated.

So if both expressions evaluate to false, the result of first expression will be returned. If only one expression evaluates true, the result of the false expression will be returned. And if both expressions evaluate to truth, the result of the second expression is returned.

  1. //Assign a value to foo only if condition evaluates to true.
  2. var foo = condition && "success";
  4. // here are some interesting expressions using logical and
  6. alert(false && 0);
  7. // false
  9. alert(0 && false);
  10. // 0
  12. alert(false && "success");
  13. // false
  15. alert("success" && undefined)
  16. // undefined
  18. alert(-1 && "success");
  19. // success
  21. alert("failure" && "success");
  22. // success

Report this snippet  

You need to login to post a comment.