Codewars Powers of 2 Simple & Easy Solution Javascript (8 kyu)

This is the solution for the Codewars Powers of 2 question in Javascript with a simple & easy to understand code and explanation.


Complete the function that takes a non-negative integer n as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to n (inclusive).

Here’s the link to the kata – Powers of 2

Solution to Powers of 2 Question:

The simple solution to the Powers of 2 question is to first create an empty array, then using the for loop store the result of 2**i (2 to the power of i, ** is same as Math.pow() ) in the array. Then, return the array.

//solution style 1 - easy to read and understand

function powersOfTwo(n){
  let arr = [];
  for(let i=0; i<=n; i++)
    arr[i] = 2**i;
  return arr;
//solution style 2 - single line

function powersOfTwo(n) {
  return Array.from({length: n + 1}, (v, k) => 2 ** k);

Leave a Comment