Cloning in JavaScript v. Cloning in Ruby

While learning JavaScript, subtle implementation differences often cause me to approach problems differently.


I’ve learned programming from the vantage point of Ruby where there is a clear built-in method for making a shallow copy of an array.


While learning JavaScript, subtle implementation differences often cause me to approach problems differently. In JS there is no function called clone or dup or even initialize_copycreated exclusively for creating a shallow copy. There are such Ruby methods. Yet, it would be naïve to think there is no such functionality.


I started solving a problem relying on operating on a cloned array. Then I took a different approach since I didn’t immediately discover how to clone the array. After solving the problem with other means I found the needed tool to clone the array. Here’s a brief description of my journey.


The Task

The Launch School curriculum tasked me with creating my own version of the JS unshift function. The intent is to familiarize the student with the implementation of built-in JavaScript functions.


unshift modifies an array by inserting a new value at the beginning of the array. The index of the new value is 0 and that of all other array values 1 more than what they were previously.

var array1 = [1, 2, 3];console.log(array1.unshift(4, 5));
// expected output: 5console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

The implementation is meant to be done using rudimentary iteration with for. No room for clever solutions. This is not an OO solution, so the new function is invoked with an array argument to be modified and not invoked on an array object itself like in the JS built-in version.


My initial process for implementation was:

  1. Clone the input array

  2. Use bracket notation to make the insertion value the first value of the input array

  3. Iterate over the cloned array

  4. Make each object at iteration the subsequent index of the input array

  5. Return the length of the array

Unfortunately, I was stopped cold at step 1.


Why a Clone?