2

Recently I was working with some JavaScript code and I found this:

<script type="text/javascript">
    window.localStorage&&window.localStorage.clear();
</script>

I did research around the web but didn't find anything about how actually that '&&' operator works if isn't in a control statement.

Does anyone know how it works?

Felipe Leñero
  • 55
  • 2
  • 12

3 Answers3

4

That's the same as:

if(window.localStorage){
    window.localStorage.clear();
}

The && short-circuits as soon as it sees a false (or "falsy") value.

So, if window.localStorage is false (or "falsy"), it stops. If it's true, it continues and runs window.localStorage.clear(). The return value is ignored.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Heeey! Thanks a lot, this is a really good trick!! There's another similar tricks? – Felipe Leñero May 25 '12 at 19:02
  • 1
    @FelipeLeñero: There's `?:`. `var c = x ? a : b` is the same as `var c; if(x){c=a}else{c=b}`. There's also `||`. `var d = a || b || c`. `d` will be set to the first not "falsy" value of `a`, `b`, and `c`. – gen_Eric May 25 '12 at 19:06
1
if this code evaluates to a truthy value&&run this code
Alec Gorge
  • 17,110
  • 10
  • 59
  • 71
0

Whether part of a control statement or not, an expression is an expression. In this case the expression involves boolean operations. So the expression will evaluate the second part if first one is true.

In this case it will execute the clear() method on window.localStorage only if window.localStorage is not null.

slowpoison
  • 586
  • 3
  • 20