Exploring conditional operators on html canvas, I am seeking a streamlined approach to dynamically change stroke color based on conditions. Online examples have not provided a satisfactory solution in a single line of code.
Currently, without using a conditional operator, I would do it as follows:
if (shape.strokecolor == 'black'){
shape.strokecolor = 'red';
}
else if (shape.strokecolor == 'red'){
shape.strokecolor = 'black';
}
In an attempt to enhance this process with a conditional operator, I discovered the following method:
var strokecol = shape.strokecolor == 'black' ?
shape.strokecolor = 'red' :
shape.strokecolor == 'red' ?
shape.strokecolor = 'black' :
shape.strokecolor = 'red';
This translates to:
- Evaluate if stroke color is black
- If true, change it to red,
- If false, evaluate if stroke color is red
- If true, switch it to black,
- If false, retain red color.
The final line in the conditional statement appears redundant to me and assigning the result to a variable seems unnecessary given that changes still take effect. My intention was to reduce the amount of code using a conditional operator, however, the current implementation does not serve this purpose effectively.
I feel like there might be room for improvement... My main query revolves around the proper usage of conditional operators without mandating assignment to a variable. Additionally, if anyone has insights on refining the existing code efficiently (with or without utilizing a conditional operator), I would greatly appreciate any guidance. Thank you.