0

trying to select a name from the "array". The output is broken in letters

var name = ["Angel", "Ben" , "Jenny" , "Michael" , "Chloe"];
var neel = name[0];
console.log(neel);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    It's a very subtle thing: The problem is that this is code at global scope and `name` is a predefined global variable on browsers that is **always** a string. So `name = ["Angel", "Ben"/*...*/]` converts the array to a string and stores the result (`"Angel,Ben,Jenny,Michael,Chloe"`) in `name` (the name of the window). Then `name[0]` gets the first letter. – T.J. Crowder May 23 '21 at 18:37
  • 1
    Solutions: 1. Use modules, which don't have this problem because `name` wouldn't be global. Or 2. Use `let` instead of `var` so that the global shadows the other global (yes, JavaScript has two layers of globals -- and browsers add several more). Or 3. Don't use `name`. Or 4. Use a wrapper function so it's not global. – T.J. Crowder May 23 '21 at 18:39

0 Answers0