{}const=>[]async()letfn</>var
BasicsJSAlgorithms

Algorithms in JavaScript for beginners

This article will explain the basic algorithms in JavaScript with simple examples. Learn how to use sorting, searching, and other popular algorithms!

К

Kodik

Author

5 min read

Algorithms are the basic building blocks of programming. They help solve problems efficiently and quickly. In this article, we will look at several popular algorithms in JavaScript and see how they work in practice. We will discuss sorting, searching, and basic principles of working with data.


What are algorithms?

An algorithm is a sequence of steps that is performed to achieve a specific goal or solve a problem. In programming, we use algorithms to sort arrays, search for values, manage data, and much more. The better the algorithm, the faster and more efficiently it works.

Let's start with the most popular algorithms that are often used in JavaScript.


Sorting algorithm: Bubble Sort

Bubble Sort is one of the simplest sorting algorithms that goes through an array, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the array is sorted.

JavaScript code example:

function bubbleSort(arr) {
    let swapped;
    do {
        swapped = false;
        for (let i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                // Swapping elements
                [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
                swapped = true;
            }
        }
    } while (swapped);
    return arr;
}

// Example of use
const array = [5, 3, 8, 4, 2];
console.log(bubbleSort(array)); // [2, 3, 4, 5, 8]

How does bubble sort work? We go through the array and compare pairs of elements. If the current element is larger than the next one, we swap them. After one pass, the largest element "floats" to the end of the array (hence the name "bubble sort"). The process is repeated until the entire array is sorted.


Search Algorithm: Binary Search

Binary search is an efficient search algorithm that is used to find an element in a sorted array. Unlike a linear search, which checks each element sequentially, a binary search divides the array into two parts and compares the desired value with the middle. This can significantly reduce the number of checks.

JavaScript code example:

function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;
    
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        
        if (arr[mid] === target) {
            return mid; // We found the element, so we return its index
        }
        
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1; // Element not found
}

// Example of use
const sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(binarySearch(sortedArray, 4)); // 3

How does binary search work? We find the middle of the array and compare it with the target element. If the element is smaller, we continue the search in the left half of the array, if it is larger — in the right half. This process is repeated until we find the element or make sure that it is not in the array.

Please note that binary search only works with sorted arrays. If the array is not sorted, you must first sort it.


Recursion: Factorial Algorithm

Recursion — this is when a function calls itself to solve a sub-task. One of the classic examples of recursion is the calculation of the factorial of a number. The factorial of the number n is the product of all numbers from 1 to n.

JavaScript code example:

function factorial(n) {
    if (n === 0) {
        return 1; // Factorial 0 equals 1
    }
    return n * factorial(n - 1); // Recursive function call
}

// Example of use
console.log(factorial(5)); // 120

How does recursion work in factorial? When factorial(5) is called, the function calls itself with the argument 5 - 1, then 4 - 1 and so on until it reaches 0. After that, the result is returned along the chain of calls, and we get the product of all numbers from 1 to 5.


Sorting algorithm: Quick Sort

Quick Sort is one of the most popular sorting algorithms that works much faster than bubble sorting in most cases. It uses the principle of "divide and conquer", choosing a reference element and dividing the array into two parts — less than the reference and more than the reference. Then both parts are sorted recursively.

JavaScript code example:

function quickSort(arr) {
    if (arr.length <= 1) {
        return arr; // Base case: an array of 1 element is already sorted
    }

    const pivot = arr[arr.length - 1]; // Supporting element
    const left = [];
    const right = [];

    for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] < pivot) {
            left.push(arr[i]); // Elements smaller than the reference go to the left array
        } else {
            right.push(arr[i]); // Elements larger than the reference go to the right array
        }
    }

    return [...quickSort(left), pivot, ...quickSort(right)]; // Recursive call for each part
}

// Example of use
const arrayToSort = [5, 3, 8, 4, 2];
console.log(quickSort(arrayToSort)); // [2, 3, 4, 5, 8]

How does quick sorting? We select the reference element (in this case, the last element of the array), and then divide the array into two parts — elements smaller than the reference and elements larger than the reference. These parts are sorted recursively until the arrays are sorted.


Conclusion

Algorithms are an important part of programming, and understanding how they work will help you write more efficient code. In this article, we looked at several popular algorithms in JavaScript, including sorting, searching, and recursion. Each of these algorithms can be used in everyday development to solve problems of varying complexity.

Try to apply these algorithms in your projects! Improving your algorithm skills will make you a more advanced developer and help you write optimized and clean code.

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card