Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Swap Two Values

Fundamentals: Part 1medium

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 11: Data Types

Implement `swap(a, b)` returning the two arguments as an array in reversed order `[b, a]`.

Sample tests

Input: swap(1, 2)
Output: [2,1]
Input: swap("x", "y")
Output: ["y","x"]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Trying to swap in place without a structure; just return the pair.

Learning resources

  • MDN: typeof
Visualize this concept: Primitives vs. References →
Approach & explanation (try first)

Returning [b, a] is the array-destructuring swap idiom, no temporary variable needed.

Loading...
⌘/Ctrl + Enter

Run your code to see results.