1

I'm curious if I can assign value within if statement, kind of:

if (a=jQuery("#user > .mask.fix > .a1").css('display')!='none'){
   b = a+'hello';
   //b=jQuery("#user > .mask.fix > .a1").css('display')+'hello'; //the same thing but  slower because of access through DOM again, right?
}

I've tested this construction in the chrome console and looks like it works. I just want somebody to confirm it is valid in javascript and even in jQuery.

Thank you.

Haradzieniec
  • 9,086
  • 31
  • 117
  • 212
  • Already asked http://stackoverflow.com/questions/2576571/javascript-assign-variable-in-if-condition-statement-good-practice-or-not – Rahul Bhanushali Mar 14 '14 at 09:53
  • @Haradzieniec...Absolutely no wrong in it. It works in C#,java,jquery or Java Script. If clause is the same in all of these – Sai Avinash Mar 14 '14 at 09:53

2 Answers2

4

I've tested this construction in the chrome console and looks like it works.

No, your first block as written doesn't do what you think it does. It assigns the result of the comparison to a, not the display value. So a will end up with true or false in it, not "none" or similar. To assign and then test, you'd need () around the (a = ...) part of it.

I just want somebody to confirm it is valid in javascript and even in jQuery.

jQuery is a library, not a language. We're just talking about JavaScript here.

You can do it like this (with the ()):

if ((a=jQuery("#user > .mask.fix > .a1").css('display'))!='none'){
   b = a+'hello';
}

...but this is much easier to read and debug:

a=jQuery("#user > .mask.fix > .a1").css('display');
if (a!='none'){
   b = a+'hello';
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • +1 Couldn't agree more, while assignments in `if` statements are possible. There can be confusion with the expected outcome and the code is harder to read. – Mark Walters Mar 14 '14 at 10:19
0

You can, but that is going to look like an error to both other programmers and to any linting tools like:

code:

var selected = jQuery("#user > .mask.fix > .a1").css('display');

if (selected !== 'none') {
    b = selected + 'hello';
}

would only run the jQuery once as well, but be a little cleaner.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38