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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Heeey! Thanks a lot, this is a really good trick!! There's another similar tricks?
@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.
1
if this code evaluates to a truthy value&&run this code

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.