Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Basic JavaScript Arrays Reminder

DZone's Guide to

Basic JavaScript Arrays Reminder

Check out this refresher for how to deal with arrays in JavaScript, which differs from other, C-style languages.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

I’m pretty bad when it comes to remembering syntax details for languages I don’t use every day, especially since I work with a few languages that use C-syntax and not just JavaScript. Also, it’s not the kind of details I want to spend a lot of time studying since this information can easily be found.

In most cases, it’s easy to look up how something is done in the project you’re working on because you’ll want to follow existing patterns anyway. But since I’m working on refreshing my JavaScript knowledge and trying new patterns, I’m often faced with a blank .js file. Arrays are always one of the first things that come up when trying to solve a problem, so I thought a quick reminder could be useful.

A standard JavaScript array is most often initialized with the bracket notation. There is also an Array object, but using the Array() constructor is not totally identical to using the bracket notation because it’s an object in that case. To keep things simple I won’t use the object, as standard arrays are a lot more common.

var fruitsArray = [];


Inserting new items at the end of an existing array is done using the push() method. The array will resize to accommodate the new items. An array can also contain any items: It is not limited to one type.

fruitsArray.push("Tomato");
fruitsArray.push("Squash");
fruitsArray.push("Potato");
fruitsArray.push("Carrot");


Removing the last item at the end of an array is done using the pop() method. In the example, the “Carrot” item will be removed.

fruitsArray.pop();


Sorting an array is done using the sort() method. By default, the items are sorted as strings, so it works for the example. For more complex cases, a sort function can be passed as a parameter to the method.

fruitsArray.sort();


Looping in an array from the start to the end using the for loop, getting the items, and printing them to the console. The example also shows the length property to get the current size of the array.

for (i = 0; i < fruitsArray.length; i++) { 
 console.log(i, fruitsArray[i]);
}


Checking if a variable is an array, printing the result to the console. This condition is useful when you can’t be sure about the type of a variable—for example because you received it as a parameter.

if (fruitsArray instanceof Array)
 console.log("fruitsArray is an array");
else
 console.log("fruitsArray is not an array");


You can find an item in an array using the indexOf() method. This method returns the index of the item in the array, or -1 if the item doesn’t exist.

var itemIndex = fruitsArray.indexOf("Carrot"); // Contains -1
itemIndex = fruitsArray.indexOf("Potato"); // Now contains 0


Finally, here are all the examples in one code snippet so you execute them and try for yourself :

var fruitsArray = [];

// Inserting items
fruitsArray.push("Tomato");
fruitsArray.push("Squash");
fruitsArray.push("Potato");
fruitsArray.push("Carrot")
console.log(fruitsArray); // ["Tomato", "Squash", "Potato", "Carrot"]

// Removing an item at the end of the array
fruitsArray.pop();
console.log(fruitsArray); // ["Tomato", "Squash", "Potato"]

// Sort the array as string
fruitsArray.sort();
console.log(fruitsArray); // ["Potato", "Squash", "Tomato"]

// Length of the array
console.log(fruitsArray.length); // 3

// Looping in an array, getting the items
for (i = 0; i < fruitsArray.length; i++) { 
 console.log(i, fruitsArray[i]);
}

// Check if a variable is an array
if (fruitsArray instanceof Array)
 console.log("fruitsArray is an array");
else
 console.log("fruitsArray is not an array");

// Search for an item in an array (returns the index)
console.log(fruitsArray.indexOf("Carrot")); // -1
console.log(fruitsArray.indexOf("Potato")); // 0


Related Refcard:

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
snippet ,code ,sort ,array ,javascript ,function ,syntax ,arrays

Published at DZone with permission of Cindy Potvin, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}