¿
rafini.clubGetting started as a web developer🌔
Index
  1. Basics
  2. Algorithms and data structures 101

Computers can only do simple operations such as basic logic and arithmetic. More complex operations are programmed by combining simple ones in certain ways way for solving specific problems.

An algorithm is a combination of steps and operations that can be used to solve a problem.

Devising an algorithm is both a creative and a technical process. A lot of problems in computer science are already solved so most of the time we can use existing algorithms.

Algorithm design is a difficult proccess and still is an active research area.

The same problem may have multiple solutions, each solution having different properties such as beign easier to implement, using less memory, or being faster.

Usually simpler algorithms are slower and consume more memory. Algorithm optimization is also an active area of research, developers usually settle for slower algorithms for the sake of simplicity.

There are even algorithms that humanity doesn't know why they work

Some popular algorithms ranging from basic to advanced are:

Arrays are one of the most commonly used data structures, an array is a collection of items such as numbers, text strings, objects, or even other arrays.

Array items are indexed, meaning that you can access individual items by their position. In Javascript and in many other languages, the first items is at index 0.

In Javascript arrays are defined by writing items between square brackets, separated by commas:

Empty and single item arrays

Note that empty arrays are valid in Javascript. To define one just write [] . An empty array has no items and length of 0

Single items arrays are not the same as the given item. For example [10] represents an array that has a single item, and that item is the number 10, instead of the number 10, so array properties and operations such as length and indexing apply instead of number ones such as addition or multiplication.

In Javascript arrays are mutable, meaning that you can change the value of an item in an array. Also, the language implement basic operations such as adding and removing items, searching for an item and much more.

You can read more about arrays in MDN
You can use any expression including other variables to index array items:
Out of bounds index

Javascript has a peculiarity over other languages, when you try to access an item that doesn't exist, returns a special value called undefined .

Operating over undefined values will result in an exception and can crash your application, so you always need to ensure that the index is greater than 0 and less than the length of the array.

Iteration is the process of repeating the same code over and over again, iteration is a very common operation when working with arrays.

The most common control flow instruction for iteration is the for loop

The for directive has 3 parts separated by a semicolon (;), all parts are optional:

  • Initialization: Runs once before the start of the loop, normally used to define a variable that will increment on each iteration such as let i = 0 . i is a commonly used variable name in for loops.
  • Condition: Runs before every iteration, if the condition is false, the loop will stop, usually a condition tests if the variable is less than the desired amount of iterations, such as i < 3
  • Increment: Runs after each iteration, normally used to increment or decrement the loop variable, such as i++

Array traversal

In computer science traversal means accesing all items of a given data structure, in this case, an array.

For iterating over an array, we want an index variable starting at 0, and we want to increment it each time we iterate until we reach the last item in the array:

If you are not interested in the item index and only want the actual item value you can use the for ... of statement as a shorter alternative:

Accumulation

Accumulation is collecting all the items of an array into a single value. Many common operations can be represented as accumulations such as calculating a sum of all items, getting the smaller or the largest item, or getting the average of all items.

Let's see how we can add all numbers in an array:

Imagine that you are writing a web app for a school and you want to calculate the average grade of all students, you can use the for ... of loop to get the sum and then divide by the number of items in the array:
Math.max(a, b) returns the largest number of the two, let's use this to also find the highest grade in the array:
You can also use accumulation to concatenate all items in an array into a single string, concatenation is the process of joining two or more strings together, you are already familiar with this operation, we use it almost on every alert() call:
Bugs

The code above has a problem, it adds a comma to the last element, so instead of printing
"Your grades are: 5, 7, 7, 9, 10, 8"
it prints
"Your grades are: 5, 7, 7, 9, 10, 8, "
Note the leading comma after the last 8 item.

A program that doesn't do what we actually want it's known to have a bug

Fixing bugs can be a tedious task, a lot of techniques are used to make it easier, such as writing simple and easy to read code, writing comments explaining what the code does, and naming variables and functions properly.

There are multiple ways of fixing the leading comma bug, skipping the comma for the first item but adding the comma before the item is one, another is skipping the comma for the last item, and leaving the comma after the item:

Skipping the comma for the last item:

Skipping the comma for the first item:

Edge cases

The code above works but fails if we change the array to an empty one, this is because it will try to access either the first or the last item on the array, which is undefined if the array is empty.

Is very common to write code that works on most conditions but fails on some specific ones, those special conditions are called edge cases.

Writing code that works on all conditions is no easy task and requieres analysis and creativity from the developer.

Some common sources of edge conditions are:

  • Empty arrays
  • Zero, negative or infinite numbers
  • Very large numbers or strings
  • Null or undefined values

Neasted loops

Is possible to write a loop inside another loop, this is called a nested loop, some problems can be solved by using a nested loop, specially when dealing with combinations.

Imagine writing an e commerce software for a clothing store, you want to display all combinations of shirt colors and sizes, finding all possible combinations between multiple arrays is a common problem that can be solved with a nested loop.

The reasoning is the following, for each size, we want to print all colors, so we first need to iterate over all sizes:

But also for each color, we need to print all sizes, so we need to iterate over all sizes inside each color iteration:

Note that we have N*M iterations, where N is the number of sizes and M is the number of colors, in this case we have 12 iterations in total.

It's too cumbersome for the user to see 12 message boxes so lets accumulate all sizes in a single string and then show the full message to the user:

while loop

The while loop is a simpler form of a loop, where instead of 3 parameters, we have only one, the condition that must be true for the loop to continue.

It's considered bad practice to use a while loop where a for loop is more appropriate, as a rule of thumb, if you have an index use a for loop, if you have a special loop condition use a while loop.

Example of a while loop used to calculate the number of months that you need to pay a loan, note that in this case we don't know the number of months beforehand, instead we break the loop when the remaining debt is fully repaid and we count the number of iterations to know the number of months

Infinite loops

It's possible to write loops that never end, this will cause your app to crash since the browser will get stuck executing the same code over and over again without having any time left to do anything else such as listening to mouse and keyboard events.

The simplest example of an infinite loop is a while with an always true condition:

Loops always need to have a way to end, either in the condition or by using a break which is an instruction that immediatly ends the current loop, without finishing the remaining code of the iteration and regardless of the loop condition.

It's not always easy to know if a loop will hang, in the above loan example, if we didn't check if the payment was enough to pay the interest, we would have an infinite loop but only in certain conditions depending on the loan amount, payment amount and the interest rate.

Arrays are mutable, this means that we can change the content of an array, basic mutation operations are:

  • Setting an item - Changes a specific item value in the array, the syntax is array[index] = newValue
  • push - Adds an item to the end of the array. array.push(newItem)
  • pop - Removes the last item from the array. array.pop()

Example of using mutation to fill an empty array:

Reverse an array

This is the first test of the course, designed to mimic interview code challenges, tests are empty functions where you need to fill the missing code.

For now don't worry about the return function syntax, it's there to make the test runnable by the page.

The page will call your function with multiple arrays and check if the result is correct.

Example input and expected output:

// This page will make a call similar to this:
let result = reverse([1, 2, 3, 4]);

// For this specific call, the expected result is:
[4, 3, 2, 1]

Here are some hints, try solving the test by reading the least number of hints!

Hint 1
Hint 2
Hint 3
Hint 4
Hint 5
Hint 6
Solution