JavaScript is without question one of the most popular programming languages in web development. Whether you are utilizing React, Vue, or Angular, it’s all just JavaScript. A broad and vital ecosystem has evolved around JS, offering tons and tons of frameworks and libraries that help you develop applications faster.

But sometimes it’s good to take a step back and try to understand how to do things without a library. Take a look at the following code snippets that solve simple problems in an elegant way and use this knowledge in daily project situations or to prepare for coding interviews.

1. Reverse a String

In this example, we are using the spread operator (…), the reverse method from Array, and the join method from String to reverse a given string.

2. Calculate a Number’s Factorial

To calculate the factorial of a given number, we make use of an arrow function and nested ternary operators.

3. Convert a Number to an Array of Digits

In this example, we use the spread operator (…), the map method of Array, and the parseInt function to convert a given number to an array of single digits.

4. Check if a Number Is a Power of Two

This one is pretty straightforward. We check that number is not falsy and use the bitwise AND operator (&) to determine if number is a power of two.

5. Create an Array of Key-Value Pairs From an Object

In this example, we use the keys method from Object and the map method from Array to map over Object’s keys and create an array of key-value pairs.

6. Return [Number] Maximum Elements From an Array

To return the maximum elements from an array, we use an arrow function that takes our array and the number of elements we want the function to return. We use the spread operator (…) and the sort and slice methods from Array. Note that if we don’t provide a second argument, number gets a default value of 1, so only one maximum element is returned.

7. Check if All Elements in an Array Are Equal

In this short example, we check if all elements in an array are equal by using the every method from Array. We basically check if every element is equal to the first element in the array.

8. Return the Average of Two Numbers

In this example, we use the spread operator (…) and the reduce method from Array to return the average of two given numbers or an array.

9. Return the Sum of Two or More Numbers

To return the sum of two or more given numbers or an array, we again use the spread operator (…) and the reduce method from Array.

10. Return the Powerset of an Array of Numbers

In the last example, we want to return the powerset of an array of numbers. Therefore, we use the reduce, map, and concat methods from Array.

As you can see, it isn’t always difficult to solve these tasks with JavaScript and some ES6 magic.

If you like what I write and want to support me and my work, please follow me on Twitter to learn more about programming, making, writing & careers🥰