This content originally appeared on CodeSource.io and was authored 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.
The post How to Swap Two Values Without Temporary Variable in Javascript appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
Ariessa Norramli | Sciencx (2021-02-21T10:06:22+00:00) How to Swap Two Values Without Temporary Variable in Javascript. Retrieved from https://www.scien.cx/2021/02/21/how-to-swap-two-values-without-temporary-variable-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.