0
I found this task on "Code Wars"

"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)."

This is what my attempt to solve the problem looks like:

function powersOfTwo(n){
  var myArray = [];

  for (var i=0; i<=n; i++){
    return myArray.push(2**i);
  }

  return myArray
}

However, it doesn't work, and I don't really understand why. I just started writing code last week to be honest.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
anon anon
  • 11
  • 1
  • 1

1 Answers1

2

You are returning inside of your loop, so it exits the function straight away. Just remove that return as you are returning the array at the end.

function powersOfTwo(n){
  var myArray = [];
  for (var i=0; i<=n; i++){
    myArray.push(2**i);
  }
  return myArray
}

const result = powersOfTwo(2)
console.log(result)
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • @J-D3V Please don't edit my answer to the point that it no longer is my answer. If you feel this could be improved to such an extent, feel free to post another answer. – Cjmarkham Sep 30 '22 at 11:12
  • You should read the answer out loud. – JΛYDΞV Sep 30 '22 at 15:41