DEV Community

Nikhil
Nikhil

Posted on • Edited on • Originally published at unsungnovelty.org

initLogs 1: Swapping numbers and reversing arrays in JavaScript

I am gonna start writing about my experiences of learning JavaScript. Most of the topics/posts are going to be super basic but what I would like to focus is the interesting connections or point of view I learnt.

And yes, thought I would categorise the series as "InitLogs" since these are the initial code/logs a lot of us will be learning and also because it will make it easy for people to look it up in case you all did find something interesting. This is also a way for me to teach/write about what I have learnt. So if you think I have to be a bit more clear or was I wrong somewhere? DM me here or @unsungNovelty.


If you're a beginner learning to code, you will eventually come across swapping numbers or reversing an array exercise. Let's look at how to do both of these in JavaScript.

Swapping two numbers

If you're not a theory person, go directly to psuedocode part!

We will be swapping the value of two variables to each other. Meaning value of the variable a will be put in variable b and vice versa. In order to do that, we need a third variable which we will call temp (for temporary). We will assign the value of a to temp after which we will assign the value of a to b and then value of b to temp.

Psuedocode

temp = a
a = b
b = temp

print a, b.

Enter fullscreen mode Exit fullscreen mode

In JavaScript

let a = 9;
let b = 0;
let temp;

temp = a;
a = b;
b = temp;

console.log(a,b);
Enter fullscreen mode Exit fullscreen mode

Reversing an array

Reversing an array can be done mainly in two ways. Reversing the array with an empty array or reversing an array in place. Reversing an array in place is without using the extra array.

Reversing an array with an extra array

The general idea is to do the same method as we did for swapping two numbers. In this reversing an array method, our temp is the variable called theReversed. We use theReversed which will start as an empty array to hold the temporary value and swap it until the numbers are swapped.

const reverseArray = (array) => {
    let theReversed = [];
    for (let i = array.length -1; i >= 0; i--) {
        theReversed.push(array[i]);
    }
    return theReversed;
}

reverseArray([1,2,3,4,5,6,9]);

// -> [ 9, 6, 5, 4, 3, 2, 1 ]
Enter fullscreen mode Exit fullscreen mode

We declare an empty array called theReversed inside the function and use the .push() method to push values during each iteration using the for loop starting from the last value of the array to the first. theReversed will end up being the reversed. As shown

Reversing an array in place

Reversing an array in place is by using the same method we used to swap numbers. But without the need of declaring an extra empty array.


const reverseArrayInPlace = (array) => {
    for (let i = 0; i <= Math.floor(array.length / 2); i++) {
        let temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = temp;
    }
    return array;
}

reverseArrayInPlace([1,4,7, 5, 7, 9, 13 ,86, 12]);

// -> [ 12, 86, 13, 9, 7, 5, 7, 4, 1 ]
Enter fullscreen mode Exit fullscreen mode

We use Math.floor(array.length / 2) to find out which one is the middle of the array. This is why we use /2, total length of the array divided by 2. Math.floor() will round off the number in case the total values in the array are in odd numbers. Math.floor() function returns the largest integer less than or equal to a given number.

And for looping through the array, we use the same method as swapping numbers. In case you didn't understand array[array.length - 1 - i], it just means the last value of the array minus the value of i which will swap the values from the array starting from the end of the array. So essentially we are swapping the front part and back part of the array while using the middle part as the pointer.

And that is it! This is how you can swap or reverse arrays in JavaScript. The connection between them was fascinating to me. Thought maybe you'll find it interesting too!

Top comments (2)

Collapse
 
steffiadhikary profile image
Steffi Adhikary

regarding "Reversing an array in place", this is not working when there are even number of elements.

for (let i = 0; i <= Math.floor((array.length / 2)-1); i++)

adding -1 is necessary here.

Collapse
 
unsungnovelty profile image
Nikhil • Edited

Hi @steffi,

Thanks for reading my post. I will admit that the const reverseArrayInPlace = (array) => {, the first line was missing the = sign. But it is otherwise working for me. Even with even number of elements. Very curious about your finding. Could you please share the code if interested? :)

const reverseArrayInPlace = (array) => {
  for (let i = 0; i <= Math.floor(array.length / 2); i++) {
      let temp = array[i];
      array[i] = array[array.length - 1 - i];
      array[array.length - 1 - i] = temp;
  }
  console.log(array);
}

reverseArrayInPlace([1,6,4,7, 5, 7, 9, 13 ,86, 12]);

// Output -> [ 12, 86, 13, 9, 5, 7, 7, 4, 6, 1 ]
Enter fullscreen mode Exit fullscreen mode