Assign Variable in If Condition Statement, Good Practice or Not

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

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:

if (value = someFunction()) {
...
}

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

if (value == someFunction()) {
...
}

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

if ((value = someFunction()) === <whatever truthy value you are expecting>) {
...
}

Assigning values for variables inside if conditional - Allways bad practice?

Always and Never rarely have a place when it comes to coding practices. Part of our job as professional developers is to maintain an appropriate balance between function, efficiency, and ease of maintenance.

I definitely agree that what you’re describing is something I would throw into the “strongly avoid” category because it certainly makes the code more difficult to comprehend and as a result introduces higher risk of bugs sneaking in during maintenance.

How to assign the value inside the if condition in vue?

This is rather a JavaScript syntax issue than Vue. While I highly recommend not assigning within a conditional, you can do so only by either declaring the variable earlier or not explicitly declaring it at all, i.e. by removing the var above.

Here's an example with your above code:

if(error = errors.description){
location.href = "/redirect?topic="+error;
}

To be clear, it is highly recommended not to do the above, or at the very least declare var error earlier so that you don't accidentally modify a global variable, like so:

let error;
if(error = errors.description){
location.href = "/redirect?topic="+error;
}

Of course the most explicit and safe solution to avoid confusion about the assignment is to simply do it earlier:

let error = errors.description;
if (error) {
location.href = "/redirect?topic="+error;
}

There has been some discussion about whether assignment within conditionals is good practice. However, on a completely separate note it is widely agreed that assigning variables that haven't been declared with var, let, or const is dangerous as you could accidentally modify variables of higher scope.

Variable assignment in an if condition

if (Derived* derived = dynamic_cast<Derived*>(base)) {
// do stuff with `derived`
}

Though this is oft cited as an anti-pattern ("use virtual dispatch!"), sometimes the Derived type has functionality that the Base simply does not (and, consequently, distinct functions), and this is a good way to switch on that semantic difference.

Assigning values inside conditional operator

No, using an assignment as an assignment is rarely a good idea - code is much easier to read and understand when conditions only test conditions, rather than when those conditions also have side-effects. In this case, you can fix it putting 2 and 0 as the expressions on the right:

const b = a === 1 ? 2 : 0;

The only time I think an assignment inside a conditional might possibly look cleaner than the alternative is when iterating over a global regular expression manually to extract matched groups (this is not using the conditional operator, but the principle is similar):

const regex = /\w(?=(\w))/g;const str = 'foo';
let match;while (match = regex.exec(str)) { console.log(match[1]);}

Why would you use an assignment in a condition?

It's more useful for loops than if statements.

while(var = GetNext())
{
...do something with 'var'
}

Which would otherwise have to be written

var = GetNext();
while(var)
{
...do something
var = GetNext();
}

How is if/while condition evaluated when we use assignments instead of comparison?

  • = is assignment operator,
  • == is comparison operator.

But assignment operator

x = y

not only assigns value from y to variable x, but it also returns that value.

Thanks to that we can write code like

x = y = z = 1;
//equivalent of:
x = (y = (z = 1));

(although it is not recommended as it can be confusing, especially for new Java programmers)

As you see 1 is first assigned to variable z, then expression z = 1 returns 1 which can be assigned to variable y. Then again assigning 1 to y returns 1 which can be assigned to variable x.

Because of that returning mechanism it is possible to write code like if (b = true) since true will be assigned to b and then returned. Since if(..) expected boolean for its condition, and found one code compiled fine.

In other words if(b=true){...} is very similar to if(true){b=true; ...}. This means that such if will always execute code from true branch (since that is what we ware assigning to b).



BONUS: How to prevent this typo?

  • omit ==true and ==false parts.

    • In case of if(b==true) we can write if(b) since (b == true) will always give same result as already stored in b.
    • In case of if(b==false) we can write if(!b).
  • use Yoda conditions if(true == b){..} where value is used before/on left side and variable on right side of ==.

    Even if by mistake we will write = instead of == we will end up with true = b which will end up as compilation error since we can't assign anything to value like true (just like we can't compile 2=3; which would attempt to assign 3 to 2 which makes no sense). We can only assign values to variables.



Related Topics



Leave a reply



Submit