Computer Science

Javascript Interating Arrays

JavaScript is a programming language that allows developers to interact with arrays, which are collections of data. Interacting with arrays involves accessing, modifying, and iterating over their elements using various methods and loops. This allows for efficient manipulation and processing of large amounts of data.

Written by Perlego with AI-assistance

4 Key excerpts on "Javascript Interating Arrays"

  • Book cover image for: JavaScript
    eBook - ePub

    JavaScript

    Syntax and Practices

    Array.prototype that provides some very useful methods to iterate over elements for an array. Iteration makes it easier to access the elements within arrays. JavaScript provides multiple ways to iterate over arrays, using the fundamental loops and predefined methods, which are topics of discussion for this section. Let's dive into it.
    5.5.3.1 Using Fundamental Loops
    The loop statements discussed as control flow statements in Chapter 2 can be used to iterate over the elements of an array. It is simple, easy-to-use way for iteration. Let us understand this using the syntax and some examples.
    5.5.3.1.1 For Loop
    One of the most basic ways for iteration is to use for loop, as array starts from index 0, so initial value is set to zero, the termination condition can be derived using the Array.length property. Similarly, the loop can also be iterated in a reversed manner using appropriate values.
    Syntax: for (let i = 0; i < array_indentifier.length; i + +) { // Execute your operations on array element }
    5.5.3.1.2 While Loop
    Another way is to use the while statement for iteration. Do not forget to specify the iteration counter inside the loop; otherwise, the loop will continue execution without stopping.
    Syntax: while(i < array_identifier.length) { // Execute your operations on array element i + +; }
    5.5.3.2 Predefined Iterator Methods
    Apart from the fundamental loops, Array.prototype
  • Book cover image for: JavaScript For Kids For Dummies
    • Chris Minnick, Eva Holland(Authors)
    • 2015(Publication Date)
    • For Dummies
      (Publisher)
    To get the value of an array element, use the name of the array, followed by square brackets containing the number of the element you want to retrieve. For example: myArray[0] Using the array definition that we created in the last section, this will return the number 5.

    Using variables inside arrays

    You can also use variables within array definitions. For example, in the following code, we create two variables and then we use that variable inside an array definition: var firstName = "Neil"; var middleName = "deGrasse" var lastName = "Tyson"; var Scientist = [firstName, middleName, lastName]; Because variables are stand-ins for values, the result of these three statements is exactly the same as if we were to write the following statement: var Scientist = ["Neil","deGrasse" "Tyson"]; To find out more about arrays, let’s practice setting, retrieving, and changing array elements in the JavaScript Console.

    Changing Array Element Values

    JavaScript gives you several ways to modify arrays. The first way is to give an existing array element a new value. This is as easy as assigning the value. Follow these steps in your JavaScript Console to see how this works:
    1. Create a new array with the following statement: var people = ["Teddy","Cathy","Bobby"];
    2. Print out the values of the array elements with this statement: console.log(people); The JavaScript Console returns the same list of elements that you put in in the previous step.
    3. Change the value of the first element by entering this statement, and then press Return or Enter: people[0] = "Georgie";
    4. Print the values of the array’s element now, using the following statement: console.log(people);
      The value of the first array element has been changed from "Teddy" to "Georgie" .
    Now it’s your turn. Can you modify the array so that it contains the following list of names, in this order? Mary, Bobby, Judy, Eddie, Herbie, Tony
    When you have lists of names, or lists of anything, there are many things that you can do with them, such as sorting them, adding to and removing from them, comparing them, and much more. In the next section, we talk about how JavaScript simplifies many of these tasks with array methods.
  • Book cover image for: Confident Web Design
    eBook - ePub

    Confident Web Design

    Master the Fundamentals of Website Creation and Supercharge Your Career

    • Kenny Wood(Author)
    • 2018(Publication Date)
    • Kogan Page
      (Publisher)
  • Now log the following statement to the console, replacing the square brackets with actual data from the array: ‘This is my array of my favourite things [List array of things separated by ’ – ‘]. There are [size of array] items in my array, and I just removed [Removed value] from the list’.

Loops

We have just explored arrays and their uses. We looked at examples of shopping lists and lists of favourite things. We also looked at retrieving that information back out of arrays and assigning it to a variable. This is useful for individual elements, but what about when we are working with large arrays with lots of data? Imagine for a second that we have a huge list of people’s dates of birth and from that list, we wanted to create a new list of people’s ages. If we had five elements in that array, we could easily retrieve each of these elements, work out their age from their date of birth, then add that age to a new array. For five elements this might not take too long. Now what would you do if we have 500 elements in an array? You might want to find a way to speed that process up. What if we could write some code that would automatically sort through an entire array and perform a specified action on each individual item inside it? All by running one single command? Or what if you have an array of objects that contains all of your navigation bar’s titles and destination links, which you need to iterate through and output to the webpage? Ladies and gentlemen, I give you ‘loops’, and with loops I also present to you the power of programming as a huge time-saver and the height of convenience. You are about to see why programming really is so powerful.

The loops

As we just discovered, loops are a way of performing an action multiple times in a programmatic way. They are a way to run a piece of code multiple times as per your requirements. They are often used alongside arrays, but their uses span far beyond just working with arrays. There are four different types of loops in JavaScript. The most common loop you will see is the ‘for loop’. Let’s take a closer look at this loop now.
  • Book cover image for: Mastering JavaScript
    No longer available |Learn more
  • Accessing array elements by an index is not a constant time operation as it is in, say, C. As arrays are actually key-value maps, the access will depend on the layout of the map and other factors (collisions and others).
  • JavaScript arrays are sparse (most of the elements have the default value), which means that the array can have gaps in it. To understand this, look at the following snippet:var testArr=new Array(3); console.log(testArr);
    You will see the output as [undefined, undefined, undefined] undefined is the default value stored on the array element.
  • Consider the following example: var testArr=[]; testArr[3] = 10; testArr[10] = 3; console.log(testArr); // [undefined, undefined, undefined, 10, undefined, undefined, undefined, undefined, undefined, undefined, 3]
    You can see that there are gaps in this array. Only two elements have elements and the rest are gaps with the default value. Knowing this helps you in a couple of things. Using the for...in loop to iterate an array can result in unexpected results. Consider the following example:
    var a = []; a[5] = 5; for (var i=0; i<a.length; i++) { console.log(a[i]); } // Iterates over numeric indexes from 0 to 5 // [undefined,undefined,undefined,undefined,undefined,5] for (var x in a) { console.log(x); } // Shows only the explicitly set index of "5", and ignores 0-4
    Passage contains an image

    A matter of style

    Like the previous chapters, we will spend some time discussing the style considerations while creating arrays.
    • Use the literal syntax for array creation:// bad const items = new Array(); // good const items = [];
    • Use Array#push instead of a direct assignment to add items to an array:const stack = []; // bad stack[stack.length] = 'pushme'; // good stack.push('pushme');
    Passage contains an image

    Summary

    As JavaScript matures as a language, its tool chain also becomes more robust and effective. It is rare to see seasoned programmers staying away from libraries such as Underscore.js. As we see more advanced topics, we will continue to explore more such versatile libraries that can make your code compact, more readable, and performant. We looked at regular expressions—they are first-class objects in JavaScript. Once you start understanding RegExp
    Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.