Why is the `const` declared outside of the function here?

Hello! My code wasn’t working (again) and I couldn’t figure out why. I looked at the solution again and realised I was placing my constant declaration inside of the function instead of outside. When and why do we place it inside the code and when and why do we place it outside? Also, how long should I be thinking about my code by myself before looking at the solution on Codecademy? I don’t know if I’m giving up to soon and losing valuable thinking time.



const greetAliens = arr => {
  for (let i = 0; i < arr.length; i++) {
  console.log("Oh powerful " + arr[i] + ", we humans offer our unconditional surrender!");
  }
}

const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];

greetAliens(aliens)
  




This should be until you feel like you’ve exhausted everything you know about the language, or you just can’t understand what’s going on. You should also look to other code information places, like the language docs.

The code works when you put the aliens array outside of the function(when you pass it in as the parameter for the greetAliens function), because you are accessing it from global scope; basically, since you are accessing from outside the function, it can’t be inside the function.

I hope this helps!

3 Likes