[Vuejs]-How to assign the value inside the if condition in vue?

0👍

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.

Leave a comment