How to Swap Two Values Without Temporary Variable in Javascript
Posted on: February 21, 2021 by Ariessa Norramli
In this article, you will learn how to swap two values without a temporary variable in Javascript.
Let’s say you have 2 variables.
// A number variable called 'a' with value 123
var a = 123;
// A number variable called 'b' with value 456
var b = 456;
In order to swap two values without a temporary variable, you can use the ES6’s destructuring assignment. In this example, you will be swapping the values of variable ‘a’ with value of variable ‘b’.
// A number variable called 'a' with value 123
var a = 123;
// A number variable called 'b' with value 456
var b = 456;
// Value of variable 'b' is assigned to variable 'a' and vice versa
[a, b] = [b, a];
console.log(a);
// => 456
console.log(b);
// => 123
Note: The ES6’s destructuring assignment functions by extracting values from its right operand and assigning them to its left operand.
Share on social media
//