admin管理员组

文章数量:1335361

I know that you can do this:

function first(a){
    a && console.log("true");
}

which is the same as:

function first(a){
    if(a){
        console.log("true");
    }
}

However, when I tried this:

function first(a){
    a && return false
}

It doesn't work, and it throws me an error. Why is it giving me an error?

I know that you can do this:

function first(a){
    a && console.log("true");
}

which is the same as:

function first(a){
    if(a){
        console.log("true");
    }
}

However, when I tried this:

function first(a){
    a && return false
}

It doesn't work, and it throws me an error. Why is it giving me an error?

Share edited Dec 6, 2011 at 1:09 Kijewski 26.1k14 gold badges107 silver badges147 bronze badges asked Dec 6, 2011 at 0:58 Derek 朕會功夫Derek 朕會功夫 94.4k45 gold badges197 silver badges253 bronze badges 2
  • 3 Better yet, use if for control flow, and && for logical and. – Thomas Eding Commented Dec 6, 2011 at 1:08
  • 1 Your first two examples have the same effect, but they aren't really the same because a && console.log("true") is an expression which returns a value (you just don't use the value in this case). – nnnnnn Commented Dec 6, 2011 at 1:43
Add a ment  | 

4 Answers 4

Reset to default 10

return can only be used in a statement on its own.

In a && return false it would be part of an expression, which is syntactically wrong.

If you really want to do it that way, you can do something like

return a && false || undefined

or for missingno's sake,

return ( a && false ) || undefined

Since && takes precedence over ||, it will be evaluated first - but parens are cool, and are always down to party.

Also, check out the spec: http://www.ecma-international/publications/files/ECMA-ST/Ecma-262.pdf - page 68 shows you how expression operators (like new) differ from statements like return (page 93)

You can get the effect you want by putting the return in the start of the line:

return a && console.log("true");

return is part of a statement and cannot be placed in a place that expects an expression (like the operand of a logical operator).

The first one only works because && is a short-circuit logical AND, this means it is only true when both expressions are true

So, if A evaluates to true (i.e., A is not null, undefined or an empty string), it will also have to check if console.log("true") is true, thus calling the method

If A is false, the expression will be false, so there's no need to call method (short-circuit)

To make it clearer, if you do

A & console.log("test") 

test will be logged no matter what A`s value is

The second does not work because it's an statement on it's own... It's the same of trying

if(A && return false) {
    //doesn't work
}

The correct way would be

return A || B;

This would return B if A evaluates to false

本文标签: javascriptWhy is x ampamp return invalidStack Overflow