Course: JavaScript

Progress (0%)

Exercise: Simple Swapping

Exercise 2 Very easy

Prerequisites for the exercise

  1. JavaScript Variables

Objective

Swap the values of two given variables.

Description

Swapping the values of two variables is a routine activity in many computer algorithms, especially the ones that perform sorting of arrays.

For instance, if a = 10 and b = 20, then after swapping these two variables with one another, we'd get a = 20 and b = 10.

In this exercise, you ought to swap the values of the variables a and b with one another.

Here's the code to get you started:

var a = 10;
var b = 20;
View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-2-Simple-Swapping and put the .html solution files for this exercise within it.

Solution

Swapping two variables with one another is an extremely easy task.

We need a temporary variable to hold the value of one variable (let's say a) while we update that variable (a) to the other variable (b, in this case).

Once the first variable (a) is updated to the second variable (b), the second variable is updated to the temporary variable.

In the code below, we create this temporary variable temp, and complete the swapping of a and b:

var a = 10;
var b = 20;

// Swap a and b
var temp = a;
a = b;
b = temp;

Let's inspect the values of a and b:

a
20
b
10

Simple, wasn't this?

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage