Skip to content
Advertisement

Assign variable in if condition statement, good practice or not? [closed]

I moved one years ago from classic OO languages such like Java to JavaScript. The following code is definitely not recommended (or even not correct) in Java:

JavaScript

Basically I just found out that I can assign a variable to a value in an if condition statement, and immediately check the assigned value as if it is boolean.

For a safer bet, I usually separate that into two lines of code, assign first then check the variable, but now that I found this, I am just wondering whether is it good practice or not in the eyes of experienced JavaScript developers?

Advertisement

Answer

I wouldn’t recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===. For example, when you see this:

JavaScript

you don’t know if that’s what they meant to do, or if they intended to write this:

JavaScript

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

JavaScript
Advertisement