Reputation:
I have this:
modalTogglePreview: function ($scope) {
if ($scope.modal.wmdPreview === true) {
$scope.modal.wmdPreview = false;
} else {
$scope.modal.wmdPreview = true;
}
}
Is there some way I could achieve the same but without the if statement ?
Upvotes: 2
Views: 136
Reputation: 816334
Aside from using the not operator as Pointy mentioned (which should be the preferred way), if you find yourself setting a boolean value inside an if...else
statement, then you are likely doing something wrong.
The condition is already evaluated to a boolean value. So your if...else
statement is equivalent to
$scope.modal.wmdPreview = $scope.modal.wmdPreview !== true;
Have a look at these examples:
var result;
if (cond) {
result = true;
}
else {
result = false;
}
This means, if the condition (cond
) is true, set result
to true
. If cond
is false, set result to false
. The value we assign to result
is exactly the value of cond
. Hence the above is equivalent to writing
var result = cond;
Now, sometimes we use conditions that don't evaluate to a boolean. To convert any value to its boolean equivalent, you can apply the not operator twice:
var result = !!cond;
Similar for the other way round:
var result;
if (cond) {
result = false;
}
else {
result = true;
}
If cond
is true, assign false
to result
. If cond
is false, assign true
to result
. This is the same as in your situation. The value we assign to result
is the opposite of the value of cond
. As Pointy showed, we can use the not operator for this:
var result = !cond;
This works with every condition, but depending on the expression, it can make it harder to read. For example, !(x > 5)
is not as obvious as x <= 5
. So if you find yourself in such a situation, you can usually flip the comparison operator.
Upvotes: 1
Reputation: 413702
$scope.modal.wmdPreview = !$scope.modal.wmdPreview;
The unary !
operator interprets its argument as boolean, and returns the boolean complement. Note that this really isn't exactly the same as your code: yours only works if the variable is exactly true
when it's tested. In my experience (for what that's worth), relying on variables used as flags in JavaScript to be real booleans is a little fragile. (There are counter-arguments however, so it's up to you.)
To explain further, the !
operator will interpret the values undefined
, null
, 0
, NaN
, false
, and the empty string ""
as being false
. Any other value is true
.
Upvotes: 12