0

I don't know if vue recognize the syntax below:

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

The code above returns a compilation error:

ERROR in ./resources/js/forms/Signup.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/forms/Signup.vue?vue&type=script&lang=js&)

Someone knows how to assign a variable inside the if else condition?

charles
  • 364
  • 6
  • 18
  • 1
    Vue is just JavaScript. The code you've provided is not valid JavaScript. Why not just move the assignment to the preceding line and then test for `if (error) {`? – skirtle May 10 '20 at 21:36
  • @skirtle I'm trying to minimize for one line only. just like in php https://www.hashbangcode.com/article/php-variable-assignment-within-if-statement. – charles May 10 '20 at 21:49

1 Answers1

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.

cuuupid
  • 912
  • 5
  • 20