惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
博客园_首页
Vercel News
Vercel News
WordPress大学
WordPress大学
美团技术团队
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Y
Y Combinator Blog
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
腾讯CDC
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Recent Announcements
Recent Announcements
雷峰网
雷峰网
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
Jina AI
Jina AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
Help Net Security
Help Net Security
N
News and Events Feed by Topic
博客园 - Franky
P
Proofpoint News Feed
L
LINUX DO - 热门话题
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
D
Docker
Google DeepMind News
Google DeepMind News
有赞技术团队
有赞技术团队
IT之家
IT之家
Security Latest
Security Latest
L
LangChain Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
4 Ways to Swap Variables in JavaScript
Dmitri Pavlutin · 2020-02-19 · via Dmitri Pavlutin Blog

A lot of algorithms require swapping 2 variables, for example, bubble sort.

During a coding interview, you could be asked "How to swap 2 variables without a temporary variable?".

It's good to know multiple ways to perform the swapping of variables. In this post, you will read about 4 ways: 2 that use additional memory and 2 that don't.

1. Destructuring assignment

Destructuring assignment lets you extract items of an array into variables. For example, the following code destructures an array:


let a;

let b;

[a, b] = [1, 2, 3];

console.log(a); // => 1

console.log(b); // => 2


[a, b] = [1, 2, 3] is a destructuring assignment that destructures [1, 2, 3] array. a variable is assigned with the first item 1 of [1, 2, 3], correspondingly b is assigned with the second item 2.

Knowing how to destructure an array, it's easy to use it for swapping variables. Let's swap the variables a and b using destructuring assignment:


let a = 1;

let b = 2;

[a, b] = [b, a];

console.log(a); // => 2

console.log(b); // => 1


[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b.

At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1]) is created.

Then the destructuring of the temporary array occurs: [a, b] = [2, 1]. The variable a is assigned with 2, and b with 1. The swapping of a and b has been performed.

I like the destructuring approach because it's short and expressive: swapping is performed in just one statement. It works with any data type: numbers, strings, booleans, and objects.

I recommend swapping variables using a destructuring assignment for most of the cases.

2. Temporary variable

Swapping variables using a temporary variable is classic. As the name suggests, this approach requires an additional temporary variable.

Let's swap the values of variables a and b using a temporary variable temp:


let a = 1;

let b = 2;

let temp;

temp = a;

a = b;

b = temp;

console.log(a); // => 2

console.log(b); // => 1


temp is the temporary variable.

In the first step, temp is assigned with the value of a. Then a variable is assigned with the value of b. Finally, the variable b is assigned with the value of temp (having the initial value of a).

The swapping of variables using a temporary variable works with any value type, like numbers, strings, booleans, and objects.

The downside of this approach is the need for a specialized temporary variable, plus the swapping happens in 3 statements.

3. Addition and difference

You can swap variables having integers without the use of additional memory (like a temporary array or variable).

The following example swaps the variables a and b using the addition + and difference - arithmetic operators:


let a = 1;

let b = 2;

a = a + b;

b = a - b;

a = a - b;

console.log(a); // => 2

console.log(b); // => 1


Initially, a is 1 and b is 2. Let's see how the 3 statements perform the swapping:

  1. a = a + b assigns to a the value 1 + 2.
  2. b = a - b assigns to b the value 1 + 2 - 2 = 1 (b is now 1).
  3. a = a - b assigns to a the value 1 + 2 - 1 = 2 (a is now 2).

Finally, a is 2 and b is 1. The swapping of a and b has been performed.

While this approach doesn't use temporary variables, it has considerable limitations.

First, you can swap integers only. Secondly, be aware of the numbers overflow when performing the addition at the first step a = a + b (the sum must be lower than Number.MAX_SAFE_INTEGER).

4. Bitwise XOR operator

The XOR operator evaluates to true if the operands are different. As a reminder, here's the XOR truth table:


┌─────┬─────┬───────┐

│ a │ b │ a ^ b │

├─────┼─────┼───────┤

│ 0 │ 0 │ 0 │

│ 1 │ 1 │ 0 │

│ 0 │ 1 │ 1 │

│ 1 │ 0 │ 1 │

└─────┴─────┴───────┘


In JavaScript, the bitwise XOR operator n1 ^ n2 performs the XOR operation on each bit of n1 and n2 numbers.

For example, here's how 5 ^ 7 evaluates to 2:


1 0 1 (5 in binary)

1 1 1 (7 in binary)

-----

0 1 0 (5 ^ 7 = 2 in binary)


Bitwise XOR has 2 interesting properties:

  • n ^ n = 0: bitwise XOR performed on the same number is 0
  • n ^ 0 = n: bitwise XOR performed on a number and zero is the same number

These XOR properties can be used to swap variables. Let's see how to swap a and b variables:


let a = 1;

let b = 2;

a = a ^ b;

b = a ^ b;

a = a ^ b;

console.log(a); // => 2

console.log(b); // => 1


Here's an explanation of why the swapping works:

  1. a = a ^ b
  2. b = a ^ b. Based on 1 a is substituted with a ^ b. Thus b = (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a. Remember that b is now a.
  3. a = a ^ b. Based on 1 a is substituted with a ^ b and based on 2 b is substituted with a. Thus a = (a ^ b) ^ a = b ^ (a ^ a) = b ^ 0 = b. The variable a becomes b.

If you find the explanation complicated, feel free to skip it. The properties of bitwise XOR (n ^ n = 0 and n ^ 0 = n) composed in 3 assignments lets you swap the values of a and b.

Swapping variables using the bitwise XOR operator has limitations: you can swap only integers.

5. Conclusion

JavaScript offers a bunch of good ways to swap variables, with and without additional memory.

The first way, which I recommend for general use, is swapping variables by applying destructuring assignment [a, b] = [b, a]. It's a short and expressive approach.

The second way uses a temporary variable. It's a good alternative to the destructuring assignment approach.

The third way, using addition and subtraction, doesn't use additional variables or memory. However, the approach is limited to swapping integer numbers only.

In the same way, the fourth approach using bitwise XOR doesn't use additional memory. But again, you can swap integers only.

What's your preferred way to swap variables?