I think that the 'correct way' will depend on the person and project. For simple problems i prefer the ternary way or the answer by @Nina Scholz.
You can also use ES6 destructuring:
({ [position]: position } = { positionOne: "positionTwo", positionTwo: "positionOne" });
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
var position = "positionOne";
function myFunction() {
({
[position]: position
} = {
positionOne: "positionTwo",
positionTwo: "positionOne"
});
document.getElementById("demo").innerHTML = position;
}
</script>
</body>
</html>
An interesting alternative using destructuring, although probably not the best for this use case, can be obtained by toggling the values of two variables:
var positionA = "positionOne";
var positionB = "positionTwo";
[positionA, positionB] = [positionB, positionA];
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
var positionA = "positionOne";
var positionB = "positionTwo";
function myFunction() {
[positionA, positionB] = [positionB, positionA];
document.getElementById("demo").innerHTML = positionA;
}
</script>
</body>
</html>
Or just use an object:
var position = {a: 'positionOne', b: 'positionTwo'};
[position.a, position.b] = [position.b, position.a];
The advantage of this solution is that enable one to change between multiple values and not just two (However for this you should probably use the solution mentioned earlier in its extensive form).
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
var positionA = "positionOne";
var positionB = "positionTwo";
var positionC = "positionThree";
var positionD = "positionFour";
function myFunction() {
[positionA, positionB, positionC, positionD] = [positionB, positionC, positionD, positionA];
document.getElementById("demo").innerHTML = positionA;
}
</script>
</body>
</html>