Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (myVar && foo()) mean in JavaScript?

(myVar && foo())

What does the above code mean? What is it equivalent to?

I think it runs on a single line.

like image 428
Val Avatar asked Jan 11 '10 22:01

Val


2 Answers

The expression evaluates to myvar if myvar is falsey, and foo() if myvar is truthy. The following snippets are nearly identical.

var x = (myvar && foo());

if(myvar){ var x = foo(); } else { var x = myvar; }
like image 173
brad Avatar answered Sep 18 '22 01:09

brad


it is an expression that equates to "if myVar is not falsey, run the function foo()". If it's used like this: var x = (myVar && foo()), the result will be:

if myVar is not falsey, x will be set to the output of foo(). if myVar is falsey, then x will be set to the value of myVar.

like image 40
glomad Avatar answered Sep 22 '22 01:09

glomad