-1

Programming noob here. Found this question on codewars: "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)."

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

Im confused as to why this doesn't work. This is probably a noob question, but i started last week

anon anon
  • 1
  • 1

1 Answers1

1

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,057
  • 4
  • 47
  • 80