0

For some reason I can't get the succinct flow control syntax to work with jQuery. The following throws an error:

$(this).hasClass('expanded') && return

Whereas this longer version works fine:

if ($(this).hasClass('expanded')) { return}

Any ideas why the first one is throwing an error?

1
  • 1
    Those two lines are very different, and personally I've never seen the first. Commented Oct 24, 2011 at 15:53

3 Answers 3

5

You cannot use the logical AND with the return statement like this. However, I can't see a reason why you would do it like that. You could just return the boolean result directly from a function

return $(this).hasClass('expanded');
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not interested in returning the result I just want the rest of the code in the block not to execute if the condition is true. I tried this and it doesn't work for me but thanks for your answer anyway, I guess I can't use this syntax with return as you say
@techjacker: well, either your example is badly choosen or I don't get it. The thing is, every function in ECMAscript returns a value. If not specified, it returns the undefined value. So, Checking for a boolean expresion to either call return or not, does not make any sense.
0

I think you could save tipying the {}:

if($(this).hasClass('expanded')) return;

1 Comment

thanks that saved a bit of typing, actually it can be made even shorter by removing the semi colon at the end if($(this).hasClass('expanded')) return
0

Each part of the boolean logical operator must evaluate to something. return can't do that.

I actually hadn't thought of using it like that before, I would have thought off the top of my head that it would work too.

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.