What is an Algorithm?

The mysterious JavaScript algorithms.

·

2 min read

An algorithm is a common formula for getting a certain result.

An Algorithm is a Formula

Such as the "formula" below for getting a string reversed (code in JavaScript):

// Problem: Reverse a string
const str = "hello";

// Step 1: split every single letter of the string to an array;
let lettersArr = str.split(""); 
console.log(lettersArr); // -> ["h", "e", "l", "l", "o"]

// Step 2: use the built-in method to reverse the array's items;
lettersArr.reverse();
console.log(lettersArr); // -> ["o", "l", "l", "e", "h"]

// Step 3: use the built-in method to join the array's items to a string;
const result = lettersArr.join("");
console.log(result): // -> "olleh"

The formula(steps/method) solves a problem and gets a certain result, it is an algorithm.

A Formula Has Many Faces

To achieve the same result, the algorithm can have many "faces". Such as we can combine the steps above to one line:

const reversed = str.split("").reverse().join("");
console.log(reversed); // -> "olleh"

To be more programmatic, we can wrap it as a function:

function reverseString(str) {
    return str.split("").reverse().join("");
}

const reversedStr = reverseString("hello");
console.log(reversedStr); // -> "olleh"

We can also write it in the new ES6 syntax, which is spreading the text string to an array:

function reverseString(str) {
    // ⛑️ ATTENTION ⛑️
    return [...str].reverse().join("");
}

There Are Many Formulas for the Same Result

Here's another formula to solve the "reverse string" problem:

function reverseStringInLoop(str) {
    let reversed = "";

    for (let letter of str) {
        reversed = letter + reversed;
    }

    return reversed;
}

const reversedStr = reverseStringInLoop("hello");
console.log(reversedStr); // -> "olleh"

The loop concept can be written in another way:

function reverseStringInLoop(str) {
    let reversed = "";

    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }

    return reversed;
}

const reversedStr = reverseStringInLoop("hello");
console.log(reversedStr); // -> "olleh"

Summary

I think the concept of algorithms in programming is simple. Like I write above, they're formulas for solving problems. But the not-easy part of algorithms is how to find that formula. I've found the hint is analyzing and solving the problems step by step. And relax.