Working with Arrays in Javascript

Introduction to Arrays in Javascript

Arrays are an important data structure in Javascript. They allow you to store multiple values in a single variable. In Javascript, arrays can hold different types of data, such as numbers, strings, or even other arrays.

Common Array Operations and Functions

Once you have an array, you can perform various operations on it. Some common array operations include:

  • Accessing array elements using their index
  • Adding elements to an array
  • Removing elements from an array
  • Iterating over an array
  • Sorting and searching arrays

Javascript provides built-in array functions, such as pushpopshift, and unshift, to add or remove elements from an array. You can also use the length property to get the number of elements in an array, and the forEach method to iterate over each element.

Here’s an example of how to add and remove elements from an array using the built-in functions:

let fruits = ["apple", "banana", "orange"];console.log(fruits); // Output: ["apple", "banana", "orange"]fruits.push("grape");console.log(fruits); // Output: ["apple", "banana", "orange", "grape"]fruits.pop();console.log(fruits); // Output: ["apple", "banana", "orange"]

Advanced Array Manipulation Techniques

Besides the common array operations, there are advanced techniques that can help you manipulate arrays more efficiently. Some of these techniques include:

  • Using mapfilter, and reduce to transform and aggregate array elements
  • Using splice to insert, replace, or remove elements at specific positions
  • Using slice to extract a portion of an array
  • Using concat to combine multiple arrays

Let’s see an example of using the map function to transform an array of numbers:

let numbers = [1, 2, 3, 4, 5];let doubledNumbers = numbers.map(function(num) {    return num * 2;});console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Codes on Tilt Shift Lens

These advanced techniques can greatly simplify your code and make it more readable and maintainable.

In conclusion, arrays are a fundamental concept in Javascript programming. Understanding how to work with arrays, including common operations and advanced techniques, will empower you to write more efficient and powerful Javascript code.

Where to start with code quality

Good quality code is a delight to work with, it is easily modified like clay to perform different actions. It is easy to debug and reason about. It is easy to understand and reads almost like a story.

Sometimes I am asked about best practices and code quality and it is a very difficult thing to explain. Furthermore, it is somewhat subjective. However I think many of the principles I learned during composition and rhetoric 101 apply to programming. Essentially good code doesn’t just happen, but it is planned and groomed into good code.

When writing an application or even a feature we have a choice about how we go about it. We could:
1. Have one large function that basically does everything
2. Write and string together functions within one file / controller that does everything
3. Write a class containing the logic needed for the feature and use class instances to perform actions

There is no universal answer to what is the right way. It’s going to depend upon the goals of the project and the scale of the feature and app. It takes time and experience to learn what is the best way for a given case and even then it’s normally not a clear cut decision. But as the expected size and life expectancy of an app / feature goes up, the more we want the code to be extensible and reusable (really this is always desired).

Writing code in self contained classes goes a long ways towards accomplishing this.

Examples of what happens given change of requirements for an application given the above 3 code choices. Let’s say we had a zoo application and we needed a way to feed and water the zoo.

Given the first style, with everything in one function we would be tempted to write the code like:

  • gets tiger food from the freezer
  • feeds the tigers
  • get bucket
  • fills bucket with water
  • water tigers
  • get lion food from the freezer
  • feed the lions
  • get bucket
  • fill bucket with water
  • water lions
  • …. on and so forth

With the first scenario if we added another animal we would likely have to add more lines of code to feed and water the animal.

Now lets look at the second style, given we have broken things up into multiple functions, we probably wrote it more like this:

Declare function feedAnimal(animal) {
getFood(animal)
feedAnimal(animal)
}
Declare function waterAnimal(animal) {
getAndFillWaterBucket()
waterAnimal(animal)
}
Declare list animals [lions, tigers, bears, ...]
for each animal in animals {
feedAnimal(animal)
waterAnimal(animal)
}

So with the second style, you can see that if we need to add more animals to the zoo, all we have to do is add them to the animal list and they will get fed.

Now let’s look at the third style.

We would write a class that had basically the same functions from the above and it might look something like this:
ZooKeeper file –
ZooKeeper {
feedAnimal(animal) {
getFood(animal)
feedAnimal(animal)
}
waterAnimal(animal) {
getAndFillWaterBucket()
waterAnimal(animal)
}
}

ZooController file –
Declare list animals [lions, tigers, bears, ...]
for each animal in animals {
ZooKeeper.feedAnimal(animal)
ZooKeeper.waterAnimal(animal)
}

In this third case adding a new animal is the same as the second, so there is not a ton of advantage in that. But our controller is a bit cleaner and probably easier to read. But our class gives us some flexibility if we need to change our zoo app around more.

Say our zoo expands so much that we now added an aquarium section. In our first case we have to write even more code and its starting to get long, jumbled and difficult to manage. In our second case we probably have to write a second controller and rewrite most of the logic from scratch again. Now this is where our third case of writing a class really helps. When we add our aquarium we don’t want to water those animal so just adding them to our animal list won’t work, but we can write a new controller and use our ZooKeeper class and we already have most of our logic done.
AquariumController file –
Declare list aquariumAnimals [sharks, turtles, eels]
for each animal in aquariumAnimals {
ZooKeeper.feedAnimal(animal)
}

So you see that the first form has an advantage in initial simplicity especially for small apps that will likely not grow. The second style is good for apps that may see limited expansion. And the third for takes a bit longer to write initially, but usually pays off as apps and features grow and change.

Using JavaScript to manipulate a webpage using tag names

This is a continuation on previous posts, Using JavaScript to Select HTML Elements, & How to use JavaScript to Interact With HTML Webpage. This will cover selecting HTML elements by tag names.

Note that I am ignoring some best practices for the sake of simplicity.

As a website loads, nodes (sections) of the page get loaded into the document object. The document object has methods that can be used to select, and manipulate the HTML page. Say we want to get all <p> tags on a website and add a smiley face to the end of each, how can we do that? The document’s method getElementsByTagName can fetch every <p> tag in a site and then we can modify each P element.

Let’s give this a try right now! Right click anywhere on this text (from a desktop / laptop) and then click Inspect from the popup menu. You should see a new window open somewhere. Inside this new window, open the console tab (See more instructions here). You can now run JavaScript code inside this console tab. In the blank area, to the left of the >, type or copy the following and then enter: document.getElementsByTagName('p').length You should see a number. That number is the total of <p> element on the webpage.

So back to adding a smiley face to the end of each paragraph.
Instead of jumping straight in, let’s do this gradually. Start by console.log each p tag:

allPTags = document.getElementsByTagName('p');
for (pTag of allPTags) {
console.log(pTag);
}

Now the output should look something like:

This is a list of all the <p> tags on the page. Now instead of console.log each of them, we can append (add) to them. We want to add a smiley face. Taking the same for loop and update it a little:

allPTags = document.getElementsByTagName('p'); // Gets all our p tags
for (let pTag of allPTags) { // Loops through each p tag
pTag.append(' :) '); // Add :) to each P tag
}

Go ahead and try it, it’s pretty funny. To undo it, just reload your page.

Next post will cover using a button to run the above code.

Need to learn more about HTML? Here is a good resource.

Using JavaScript to Select HTML Elements

One of the most common uses of JavaScript to manipulate elements on a web page. As we learned in the interact with the DOM post, the fist step to manipulating an HTML element is selecting it. The document object that is built into web browser’s JavaScript provides multiple methods that can be used to select an element.

I think it’s important to mention that you will commonly see jQuery mentioned in connection to selecting HTML elements. jQuery is a library (collection of methods and functions) that abstracts many commonly needed actions. I will not cover the use of jQuery in this post as I want to focus mainly on vanilla (plain) JavaScript. Under the hood, jQuery uses the same methods covered here. Old browser versions had inconsistencies in the document object and it’s methods that jQuery helped resolve. Most of these issues have been resolved and the methods covered here are included and standardized across all modern web browsers.

It is assumed that you have a basic understanding of HTML and CSS. If not, then you may find the following difficult to follow. I have placed some excellent HTML and CSS links here that will aid your HTML learning.

getElementById

The method getElementById is the easiest selector method to use. As the name suggests, it finds an element by using its id. Because every ID on valid HTML a page is unique, you know exactly what element it is returning. Of course the element you want to get must have an ID.

The getElementById method takes a string for a parameter and returns the element directly.

Take a look at this interactive code snippet:

See the Pen KbyWYB by Matthew Wilson (@matw) on CodePen.

We have an HTML paragraph with an ID of “foo”. To select this element we use the method getElementById and insert the name of the ID (in our case “foo”) as the first and only parameter. var mySelectedElement = getElementById("foo");.

So now mySelectedElement is set to our HTML element. Our element has many properties, but since in this example we want to change the color we need to update style.color. This can be reassigned to change the elements color and in our example we set it to equal “red”. If you are curious about the other properties on HTML elements see my post here.

getElementsByClassName

Because many elements on a page do not have an id, I find myself using getElementsByClassName a lot more frequently than getElementById. As you might guess from the name, this method returns an array-like-object that contains a collection of elements. This is unlike getElementById which directly returns one element. This means that if you are wanting to select one particular element, you will need to select it from your returned object, however in many cases you may want to perform an action on multiple elements. If this is the case and all your elements have the same class, then the getElementsByClassName works out well.

Let’s look at an example. Say we have a list of names and passwords and we want to hide the passwords on the click of a button. We could do something like this:

See the Pen
Using getElementsByClassName example
by Matthew Wilson (@matw)
on CodePen.

The document.getElementsByClassName('secret') returns an object populated with all the elements that have the class “secret”. We can then use a for..of loop to change the style of each element.

You should also know that getElementsByClassName can be called, not only from the document object, but from any element. It is important to note that it only finds matches that are children of the calling element’s node. This behavior is useful in many situations. Extending the previous example, let’s make our password list have several sections that can be hidden individually. Also let’s reverse the action, instead of hiding our passwords, let’s reveal them on click.

See the Pen
Using getElementsByClassName with children
by Matthew Wilson (@matw)
on CodePen.

There are a few things here that at first may not be clear, so let’s take a closer look. We are using a special keyword “this” as the first parameter in our on-click handler. If you look at the HTML you will see our button section looks like <button onclick="showSecrets(this)">HIDE SECRETS</button>. Here the “this” is actually sending in the button element as a parameter to the showSecrets function. Now we have our calling element inside our function and can use that to our advantage. Since our button and our list items both have a common parent element (the surrounding div) we can use that parent element to call getElementsByClassName and reveal only the passwords in that section.

As you can see from this example, we can use getElementsByClassName’s descendant-only matching behavior to our advantage. If it found every match on the page, we would have to use separate class names or another method to select only one section of passwords to reveal.

Coming soon – Part 2
getElementsByTagNames & querySelector

How to use Javascript to Interact With HTML Webpage

One of the most useful aspects of JavaScript is its ability to manipulate a website. When a pure HTML website loads, that’s it—it’s done and it will not change again until the page is reloaded. Adding JavaScript to a page, however, gives us the ability to update a page even after it has been completely loaded. We’re going to be using the Chrome devTool’s console for this post, so if you don’t know how to open it and use it, please check out the console post for more info.

The HTML Document

The HTML document is composed of elements that are created using tags. HTML tags have the standard format <tagname>Content</tagname>

, and they describe the type of content they contain. For example, to indicate the beginning and end of a paragraph, the content is wrapped using a “p” tag: <p>The paragraph goes here.</p>. W3 School has a great in-depth article here covering HTML tags.

When using JavaScript to manipulate an HTML document, we can use the tags as a road map to navigate and select the document section we want to manipulate.

What is the DOM

When dealing with JavaScript and HTML you will likely hear people refer to the DOM. DOM stands for Document Object Model, and it is essentially an interface that allows JavaScript to access the web page “document.”

To illustrate this point, imagine a string puppet for a minute. If you think of a web page as a puppet, then the DOM could be thought of as the strings and the points at which they attach to the puppet.

Using this same analogy, JavaScript would best be compared to the stick that controls the strings. The DOM allows us to connect JavaScript and HTML together.

Included with a browser’s JavaScript version is an object called the “document.” It is on this object that we can find methods that allow us to interact and manipulate the DOM. Continuing with the analogy, the puppet control sticks have multiple “methods” or actions that can be used to manipulate the puppet.

The DOM is made up of elements that are connected in a tree-like structure. The elements of this tree are objects, and they can be accessed from the root document object mentioned in the previous paragraph.

Navigating the DOM

Before we can manipulate a section of the DOM, we first need to know how to select an element. To help with this, I’ve made a very simple web page that you can experiment with: http://matw.me/example.html. Open this page in a new tab and follow along.

Here is what the HTML code of this example.html page looks like:

<!DOCTYPE html>
<html>

  <head>
  </head>
  <body>
    <div>
      <h1>Div 1 Heading 1</h1>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </div>
    <div>
      <p>Div 2 Paragraph 3</p>
      <span>
        Text inside span 1.
        <span style="color: blue;">I am a span within a span.</span>
      </span>
    </div>
  </body>
</html>

As you can see, it’s a fairly simple page. There is an inline style to color the nested span blue, but not much else is going on. First off, let’s change the text of the first paragraph.

Before we can manipulate the first paragraph, we have to select it. There are many ways to select an element on a page—you can get elements by class name, id, tag name, or by “walking” up and down the DOM tree. Since the “document” is the DOM root, everything on the web page is a child of the document.

This may be a bit difficult to understand, so let’s take a closer look at it. Go to the example.html page and then open the console. Then type in document.children and press enter. The console should look something like:

Now click the triangle to expand the HTMLCollection object. Can you see how it compares to our HTML code? The first and only child element is the “html” object. This is the root from which everything else on the page stems. Since this is an object, we can save it to a variable. To do that, use var htmlRoot = document.children[0] and press enter. We have to add [0] to the end of our document.children because we want the first child. In JavaScript, the first item is item 0. Now our variable htmlRoot is a reference to the DOM’s html object. Looking back at our page code, you can visualize what this variable references on the page.

Let’s take a look at the HTML’s hierarchical structure:

In the console, we can view the content of our htmlRoot variable. Enter htmlRoot and you should see:

In a tree form, this would look like:

As you can see in the tree above, “html” has two children: “body” and “head.” If we want to navigate to the first paragraph, we have to go through the “body” and then the first “div.” The first paragraph will then be the second child.

Let’s return to navigating to our first paragraph element, and take it one step at a time. Remember the htmlRoot object we created earlier? This is the html element at the top of our tree, so if we enter htmlRoot.children, we should see that htmlRoot has two children: “head” and “body.”

We already know we want the body, which is the second child. Since our index starts at 0, htmlRoot.children[0] would refer to the head, and htmlRoot.children[1] would refer to the body. Let’s save the body as a new variable. We can do that with var body = htmlRoot.children[1], and pressing enter.

Now let’s look at our body variable:

All the code entered to get here is recapped at the bottom of the page.

Well, I think that’s pretty neat. We now have a JavaScript variable that represents the HTML “body” element. Now to get that first paragraph, we need to go to the first child of the body, which is a “div” and then the second child of that div would be our paragraph (p element). That will be:

var firstDiv = body.children[0]
var firstParagraph = firstDiv.children[1]

In the console it would look like:

As you can see, we finally have our paragraph saved as a variable! Now we can manipulate the text, style, class, id, or other attributes of our “p” element. This style of selecting an HTML element by going up or down the tree using children or parent selectors is called “walking the DOM.” There are other ways to select elements on a page, but I will cover these in future posts.

Changing An Element’s Text With JavaScript

Let’s update the text in our first paragraph to say “Hello World.” Even though navigating the DOM and selecting the first paragraph was somewhat complicated, changing the text itself is very easy. The paragraph element, which is of course an object, has a property “innerText.” If we type firstParagraph.innerText, we will see the current text of the element returned.

We can simply set this innerText to our new value and it will update the page.

firstParagraph.innerText = "Hello World"

Instantly, our text gets updated to “Hello World”.

Recap

In order to update a section of text on the screen, the first step we need to take is selecting the element’s DOM object. Then we can reassign the inner text. For this page, it looks like:

What’s next?

There are lots of methods that can be used to select elements from the DOM, and while many of them would have made selecting this element easier, in my opinion it is very important to learn how to navigate the DOM using a simple straight “walk down” as demonstrated here. Learning this method helps provide an understanding of what the DOM is and how it is structured.

In my next post, I plan to go over other “document” methods that will make navigating and manipulating the DOM simpler and faster.

In the meantime, play around with selecting DOM elements and updating them. Share some screenshots in the comments section.