JavaScript Array.prototype.unshift()

Array.prototype

unshiftThe JavaScript unshift method adds the specified value to the beginning of the array and returns the new length of the array. It is the most efficient way to add an element to the beginning of a JavaScript array.

While some may be tempted to use the Array.prototype.splice() method to add an element to the beginning of a JavaScript array, you can trust me when I say, the Array.prototype.unshift() is the way to go. I will add though, just as an observation, I’ve always felt that the method name “unshift” is clunky and unintuitive. Nevertheless, it is the one that the ECMAScript specification has given us, so we’ll just have to hold our noses : – ) and dive right in.

So, the syntax for the Array.prototype.unshift() method is quite simple. You just chain unshift() onto your array variable name, and pass one argument to that method: the element that you want to add to the beginning of your array. For example: myArray.unshift(“hello”) would add the string “hello” to the beginning of the “myArray” array.

So you can pass any valid JavaScript value as the argument to the unshift() method. This could be a number, an object, another array or even an expression such as an executed function. But it’s important to keep in mind that the unshift() method returns the new length of the array.
So, if an array has five elements, calling the unshift() method will return “6”, because adding one element to that array has increased the length of the array to “6”.

Try it yourself !

In the above example, click the JavaScript tab. You’ll see that we have the foo array, which has three elements. Each time that we call the unshift method, the value that we pass as an argument is added to the beginning of the array. Notice that we show the return value of the unshift method in the console. This allows us to see that shift returns the new length of the array.

Click the Result tab. Notice how we call the unshift method a total of three times. Each time, we show the return of that call to unshift: “4”, “5”, and “6”. We also show that we use the console.dir method to inspect foo. This is so we can see the changes that are happening to the array with each call to unshift.

Video Example Code

If you want to download the example code, visit this page: bit.ly/kcv-array-unshift

Summary

So, big picture: the ECMAScript specification provides a number of methods on the Array.prototype object that are designed for handling mutations to the beginning and end of an array. The Array.prototype.unshift() method, for example, is specifically designed to efficiently add an element to the beginning of an array. The way it works is, the element that you pass as the sole argument is added to the beginning of the array, and the new length of the array is returned. Simple and efficient… that’s what we like, right?

JavaScript Array.prototype.splice()

Array.prototype

javascript spliceJavaScript’s Array.prototype.splice() method removes one or more elements from any position in the array and returns the removed elements in a new array. It also allows you to add one or more elements to the middle of an array.

JavaScript’s Array.prototype.shift() and Array.prototype.pop() methods allow you to remove elements from the beginning and end of a JavaScript array. These methods are simple to use and require no arguments because there is no potential for ambiguity: the concepts “first element” and “last element” require no further explanation. But when you want to remove one or more elements from the middle of a JavaScript array, there are details required. For example: where in the array do we want to start removing elements? Also, how many elements do we want to remove?

The Array.prototype.splice() method answers that question by removing one or more elements from any position in the array and returning the removed elements in a new array. Initially, this can throw you off because if you want to remove only one element, you would expect just that one element to be returned. But the Array.prototype.splice() method always returns an array. So, just keep in mind that if you plan to remove one element, you’ll need to access the first element in the array that is returned.

The syntax for this is simple: you just pass a minimum of two numbers to the splice() method: the position in the array at which you want to start removing elements, and the number of elements to remove. In this case, you are only removing elements from the array. But you do have the option of adding as many additional parameters as you like. So, beginning with the 3rd parameter, you specify one or more elements to ADD to the array, starting at the position specified with the first parameter. For example: myArray.splice(2, 3) would remove three elements from myArray, starting at index # 2. But, myArray.splice(2, 3, ‘a’, ‘b’, ‘c’) would also add the strings ‘a’, ‘b’, ‘c’ to the array starting at index # 2.

JavaScript’s Array.prototype.unshift() and Array.prototype.push() methods allow you to remove elements from the beginning and end of a JavaScript array. But if you want to remove elements from the middle of an array, the Array.prototype.splice() method is the correct tool. In this case, you provide a zero as the 2nd argument, which means that you are saying: “I do not want to remove any elements from the array”. If you provide any arguments after the 2nd argument, however, then those will be added to the array starting at the position specified in the 1st argument. For example: myArray.splice(2, 0, ‘HELLO’, ‘GOODBYE’). Here, you’d be adding the strings ‘HELLO‘, ‘GOODBYE‘ to the array starting at position # 2. But keep in mind that in this case, the Array.prototype.splice() method will return an empty array, because that method always returns an array. But if you do not remove any elements from the original array, then an empty array is returned.

Try it yourself !

In the above example, click the JavaScript tab. There we call the splice method on an array. In the first case, we take a very simple approach; the first argument is 0 and the second argument is 1: foo.splice(0, 1). This is similar to using the JavaScript shift() method, except that shift() returns the removed element, whereas the splice() method returns the removed element in an array.  This is a very simple example, but the main takeaway is: the first argument is the position to start at, and the second argument is the number of elements to remove.

Later in the examples, we pass no arguments to the splice method. In this case, no elements are removed from the original array and an empty array is removed.

Click the Result tab to see the output for all of the splice method examples.

Starting from the end of the array

In the last example, we provide a negative number for the first argument. A negative number tells the splice method that we want to “start at the end”.  For example:   foo.splice(-4, 3)  tells that splice method that we want to start at the fourth-to-last element in the array, and remove three elements.

Summary

Working with the beginning or the end of a JavaScript array is fairly straightforward, and to make matters even better, the Array.prototype’s push(), pop(), shift() and unshift() methods simplify the process. It’s when you want to remove or add elements to the middle of an array that things can get a bit more complex. Fortunately, though, the Array.prototype.splice() method provides a way to remove one or more elements from or add elements to the middle of a JavaScript array. But the key thing to remember is: this method always returns an array. So, if you are removing elements and you want to access any of the removed elements, you’ll need to iterate the returned array. But if you are adding elements only, then an empty array will be returned.

JavaScript Array.prototype.shift()

Array.prototype

shiftThe JavaScript shift method removes the first element from the array and returns that element.

While it may be tempting to use the Array.prototype.splice() method to remove an element from the beginning of a JavaScript array, believe me, Array.prototype.shift() is the best way to do it. And just as a side note, I’ve always felt that the method name “shift” is a little odd, but that’s what the ECMAScript specification calls for, so we’ll just move along with the good stuff.

So, with the Array.prototype.shift() method, it’s the syntax that’s really important, and the beauty of it is, it’s quite simple. You just chain .shift() onto your array variable name, without passing any arguments. For example: myArray.shift() would remove the first element from the beginning of the “myArray” array. Just keep in mind that the .shift() method returns the element that was removed from the beginning of the array. So, for example, if an array has five elements and the first one is the string “ABC”, calling the .shift() method will return “ABC”, because it has removed that element from the beginning of the array.

Try it yourself !

In the above example, we have the foo array, which has six elements. Each time we call the shift method, the first element of that array is removed. Notice that we show the return value of the shift method in the console. So, we can see that shift returns the element that was returned.

Click the Result tab. Notice how we call the shift method a total of three times. Each time, we show the return of that call to shift: “a”, “b”, and “c”. We also show the length of the foo array each time as well. That length decreases each time we call shift, so the values are 5, 4, and 3. And finally, each time we call shift, we use the console.dir method to inspect foo, so that we can see the changes that are happening to the array with each call to shift.

Video Example Code

If you want to download the example code, visit this page: kcv-array-shift-fiddle

Summary

So, to recap, the ECMAScript specification provides a number of methods on the Array.prototype object that are designed for handling mutations to the beginning and end of an array. But the Array.prototype.shift() method specifically functions to efficiently remove the first element from the beginning of an array. This method takes no arguments and returns the element that was removed from the beginning of the array. Simplicity and efficiency at its best!

JavaScript Array.prototype.join()

Array.prototype

javascript joinThe JavaScript join method converts an array into a string.

Converting an array to a string in JavaScript may seem like an unlikely scenario at first, since they are dissimilar types, but this is not as uncommon as one might think. I’ve found that when I want to build a complex string, organizing the various parts of that string into array elements can be a helpful approach. For example: I have to build many vanilla JavaScript applications that feature custom CSS. The CSS is completely managed by the JavaScript code, but I ultimately inject a new STYLE element into the page, with the custom CSS as the content of that element. In building these custom styles, I organize each CSS rule into a string that is an element of an array. Then, after all of the custom CSS rules are created, I use the join() method to combine all of those array elements into one long string, and make that string the content of the STYLE element that is injected into the page.

At first glance, it may seem a bit odd to use a space, hyphen or forward slash as the separator, but as a developer, you are likely to find yourself in many situations in which the business requirements require you to solve unexpected problems. Converting a number of array elements to a string and separating each element with an odd character will be a challenge you will run into, so be prepared; if it has not happened yet, it will! Fortunately, the Array.prototype.join() provides an elegant solution to this problem.

If you pass no arguments to the JavaScript join method, then there will be no space between the characters of the string. Or, you can pass an argument that determines how to join the elements of the array. Which character(s) you provide is up to you. The most common practice is to use the default, which is a comma (” , “ ), but again, the choice is completely yours.

Try it yourself !

Click the JavaScript tab in the above example. We have an array with six elements: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]. When we call the join method on that array in the first console.log statement, it returns the string: “a,b,c,d,e,f”. This is the default behavior. That is to say: when you do not provide a separator argument, the characters in the returned string are separated by a comma  (” , “ ). In the following examples we do provide a separator argument. In each case, you will see that the separator is used to create the returned string.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-javascript-array-join-fiddle

Summary

String manipulation in JavaScript can be tedious, as converting an array to a string is a problem that might tempt one to use a for-loop as a solution. But the Array.prototype.join() method was specifically designed to solve this problem, as it negates the need for any kind of for-loop or other iteration patterns. You can simply chain the join() method from your array reference and then pass a character as an argument, which tells the join() method how you want to separate the elements of the array when converting to a string. In the long run, it really is a smooth way to go.

Introduction to the JavaScript Array reduce() method

Array.prototype

JavaScript LogoJavaScript’s Array reduce() method can be a bit confusing. It doesn’t “reduce” any of the array elements, in fact they are not changed. This method “reduces” the array to one value.

An array is essentially a list, and in JavaScript, that list can contain any valid value. Most array-specific tasks involve “doing something” with the array, or you may need to “do something” with every array element. But what if you need to convert the array into one value? In other words, if the array contains a list of values, what one value could represent all of those values? In this article, I’ll explain how the JavaScript Array reduce() method provides a way to solve this problem.

An important concept to think about is how you can translate a list of values into one, that represents all of them. In some languages, all arrays must be “typed”. In other words, every array element must be of the same type. In JavaScript, you’re not limited in this way; a JavaScript array can contain any number of numbers, strings, arrays or any other valid JS value type.

It’s true that Typescript can limit this kind of freedom, but you’re not required to use Typescript and ultimately, Typescript compiles down to JavaScript. So, the reality of dynamic arrays in JavaScript has not changed. Therefore, if you want to reduce all of the values in your array to one, it’s important to consider the type of each element. If all of the elements in your array are of the same type, things are fairly simple. If the types vary, however, that can get complicated. Of course, that discussion is beyond the scope of this article, but I just wanted to point it out.

Using a while-loop – Example # 1

See the Pen Array.prototype.reduce() – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

A “while” loop is a valid way to iterate a JavaScript array and that approach has worked for us here. We effectively “reduced” all of the elements of our array to the one value of 79, and we did this by adding each array element to the “getTotal” variable.

When I said that this approach “…has worked for us”, you may notice that I didn’t say that it “…worked well”. This is because the approach we took solved a problem, but created a couple of issues, the main one being boilerplate code. Most of the code in our “while” loop will be repeated if / when we need to solve the same problem elsewhere in our code. In addition to that, we have created an “i” variable to keep track of our counting during our “while” loop. It may seem innocent, but the more variables we create, the more variables we need to manage. Fewer variables is better.

Using the JavaScript Array reduce() method – Example # 2

See the Pen Array.prototype.reduce() – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

The Array reduce() method has dramatically simplified things in Example # 2. Notice how, in the getTotal the variable is now an anonymous function. In this function, we add the accumulator and currentValue arguments. Now you may be wondering: “What are the accumulator and currentValue arguments?” Well, take a look at the last line of code: milesPerDay.reduce(getTotal). What’s happening here is, we’re executing the .reduce() method of our “milesPerDay“, passing it the getTotal as an argument. This is the anonymous function that we detailed a few sentences ago.

So, the reduce method iterates the array and provides access to not only the currently iterated value (i.e. the current array element), but also the value that was returned by the previous execution of this function. This allows you to “accumulate” values across the array.

The arguments passed to the JavaScript Array reduce() method –
Example # 3

See the Pen Array.prototype.reduce() – Solution – 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 3 does not provide any additional value with respect to solving the problem; the solution from Example # 2 is solid. The purpose of Example # 3 is to offer more detail about the arguments that are passed to the function provided to the Array reduce() method.

As demonstrated in the UI, the first argument is the accumulated value that’s being created as you iterate the array (i.e. the value returned by the last execution of this same function). The second argument, “currentValue”, is the value of the current array element. In the third, the index of the current array element is provided, and in the last, we see the array over which you are iterating.

I decided to show the value of the “array” argument to demonstrate that the Array reduce() method does not itself make any changes to the original. You can do that within the function passed to the Array reduce() method, but reduce() itself does not make any such changes. What you choose to do with these arguments is up to you, but just know that they’re helpful in building the logic you need to reduce your array to one final value.

Introduction to the JavaScript Array map() method

Array.prototype

JavaScript LogoJavaScript’s array map() method allows you to “do something” with each element of an array. This has always been possible, but the map() method’s syntax is simple and elegant.

When you have an array, you’ll eventually want to “do something” with it. You may, for example, want to do something with the entire array, such as showing all of its elements in the UI. But what about when you want to “do something” with each element in that array? This poses a bit more of a challenge.

First, you’ll need to iterate the array, which requires some kind of loop. Second, you’ll need to keep track of your iteration process, which requires a counter variable (which requires you to control that variable’s scope). This may seem like no big deal, but it’s work and each time you want to solve the same problem, you’re writing code that’s virtually identical, but not entirely the same, so you start to copy and paste.

This kind of repetitive boilerplate code is tedious, it must be managed, and as repeated code, it becomes a red flag. So, since this kind of coding presents unnecessary problems, what we’ll cover in this article, is how the JavaScript Array map() method solves these issues.

Using a for-loop – Example # 1

See the Pen Array.prototype.map – Challenge – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Our first pass at this solution employs a for-loop. As mentioned above, this introduces a few problems. We have the “i” variable, for instance, which in this example is a global. In a real-world situation, however, we would want to put this code in a function so that the “i” variable does not wind up in the global scope. Also, the code in our for-loop is tedious. We need to use the “i” variable to keep track of the currently iterated rawNumbers element. There’s definitely a better way to go about this.

Using the Array map() method – Example # 2

See the Pen JavaScript Array.prototype.find() – Solution 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 2, we use the JavaScript Array map() method to solve the problems discussed. We’ve passed an anonymous function to that method, and this anonymous function takes the currently iterated number as its first argument. Inside of our function, we have some simple code that rounds the currently iterated number.

The biggest benefit to using the JavaScript Array map() method is that we no longer have the “i” variable or the for-loop. This is already a major improvement, especially the reduction of code, since it means that it’s simpler and easier to read. These are not minor details, and if this is a task that occurs multiple times in your application, you’ll soon find that the benefit gained by reducing repetitive code will quickly become significant.

Passing a function to the Array map() method – Example # 3

See the Pen Array.prototype.map – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

The approach in Example # 3 is similar, but there’s one big difference: instead of passing an anonymous function to the Array map() method, we pass to the Math.round method, which makes our code even easier to read. This is largely because we leave the implementation details to Math.round and eliminate even more code: our anonymous callback function. There are two reasons that we can do this: Math.round takes a number to round as its first argument, just like our anonymous function, and it returns the rounded number, just like our anonymous function. Simplified code is better code and in this case, we have Math.round to thank for that.

Introduction to the JavaScript Array find() method

Array.prototype

JavaScript - find methodJavaScript’s Array find() method allows you to find the first element that matches logic provided by you.

When you have an array of values, it’s likely that you might need to find an element in that array. In particular, you might want to know which element in this array meets a certain criterion. Well, the criteria are up to you. For example, if your array contains numbers, you may want to know how many of the elements in that array have a value higher than a certain amount. Well, in this article I’ll demonstrate the JavaScript Array find() method, which provides a straightforward way to confront this problem.

Iterating an array usually requires counting. This makes sense, because in order to “do something” with every element in the array, you have to know how many elements are in there (i.e. the array’s “length”). Then you have to keep track as you count up to (or down from) the length of the array. This approach is perfectly valid, but it comes with problems.

The first problem is that setting up a loop of any kind creates boilerplate code, then you need a counter (i.e. “i” or “j”), and finally, you need logic that uses the value of your counter to determine whether or not your target elements have been found. Just discussing this in a “pseudocode” context is tedious, and writing the actual code is even more so. But the JavaScript Array find() method solves this problem, as it removes the need for tedious boilerplate code.

Using a while-loop – Example # 1

See the Pen Array.prototype.find() – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

The tedious boilerplate code we discussed above is exactly what you find in Example # 1. We’re using a while-loop to iterate over the someNumbers array. On each iteration of the loop, we use the value of “i” to examine the currently iterated array element and determine if it meets the criteria for our search. This code is valid and it works, but it’s less than optimal.

Using the Array find() method – Example # 2

See the Pen Array.prototype.find() – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 2, we use the Array find() method to eliminate the problems introduced in the previous example. We’ve passed an anonymous function to the Array find() method, and this method takes the currently iterated element as its first argument. Inside of this anonymous function, we provide some logic that determines the currently iterated array element, then we decide whether or not it meets the criteria for our search. The first big benefit here is that we’ve removed the “while” loop. Also, we no longer have the “i” variable. These may seem like small details, but every variable takes up memory, and has scope.

As we know, JavaScript scope is controlled by functions, or blocks. So, for any variable we use, we need to either create a function to control its scope, or carefully initialize that variable in the right function. So the main benefits of the Array find() method are the simplified syntax in which verbose boilerplate code has been removed, and working with our more elegant JavaScript, which is easier to follow.

Introduction to the JavaScript Array filter() method

Array.prototype

JavaScript array filterWith the Array filter() method, you provide a function that returns an array containing the “filtered” elements. It is within this function that you provide the logic that determines how your original array is filtered.

Sometimes you have an array, but want to reduce the number of elements you work with, based on a certain logic. For example, you may have an array with the days of the week, but you only want to work with the days that start with the letter “T”, which means that you only want the elements “Tuesday” and “Thursday”. Well, JavaScript’s Array filter() method provides a simple and elegant interface by which you can solve this problem. In addition to the straightforward syntax, the Array filter() method eliminates the need for boilerplate code such as a for-loop. To further explain, we’ve demonstrated this in the code examples that follow.

Using a for-loop to filter an Array -Example # 1

See the Pen Array.prototype.filter- Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 1, we use a “while” loop to iterate the word’s array. “While” loops are perfectly valid in JavaScript, but they always make me nervous, because whenever I’ve started to use a “while” loop, I immediately ask myself: “is there a better way to do this?” The main reason is that with a “while” loop, if you’re not careful and your “while” logic is faulty, the loop could theoretically run forever. This is a bit off-topic, but I just like to point out that it’s important to use “while” loops with care.

Back to Example # 1. Inside of the “while” loop, we use the value of “i” to determine if the current word should be pushed to the “shorter” array or the “longer” array. Once this loop has completed, we update the UI to show the number of “shorter” and “longer” words. Again, perfectly valid code, but kind of verbose and less than optimal.

Using the Array filter() method -Example # 2

See the Pen Array.prototype.filter – Solution # 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 2 is a major improvement over the previous code. We leverage the Array filter() method to determine the number of “shorter” and “longer” words. There are a couple of areas of improvement here.

First, we’ve removed the need to manually push words to the “shorter” and “longer” arrays, because of the simple syntax of the Array filter() method. Notice that as we create the “shorter” and “longer” arrays, we assign the value by executing the Array filter() method. We provide an anonymous function to the Array filter() method, and the logic is simple: the sole argument passed to that anonymous function is the iterated word, and inside of the function we simply determine if the word’s length is greater than or less than five.

Second, we’ve removed the “while” loop. This is a major improvement, given the fact that it reduces the amount of code, but also since there is no longer any possibility that our code will run forever because of the use of a “while” loop.

Passing a function to the Array filter() method – Example # 3

See the Pen Array.prototype.filter – Solution # 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

The winsPrize() function approach of Example # 3 differs a bit. Instead of using an anonymous function when executing the Array filter() method, we pass a function declaration. Also, we’ve chained the Array filter() method off of an array literal (in other words: we create the array and then immediately execute the filter method). This is not necessarily a “more correct” approach, it’s just less verbose. The logic of the winsPrize() function is similar to the code in Example # 2. The main difference is that we pass a function declaration instead of an anonymous function.