0

I am trying to write a simple program in Javascript which will take 10 inputs from user and stored in an array and then display the input in console.

Below the code which I have already write:

var name = [];
for(var i =0; i<=10; i++){
    name[i]=(prompt('Enter your name'));
}
console.log(name);

But it is not showing any values and I have tried to console values of i inside the for loop.
It is showing undefined in console. Please help me to solve this issue. Thanks.

iHasCodeForU
  • 179
  • 11

2 Answers2

2

You must be running that code at global scope in a browser. name is already defined in the global namespace on browsers. It's the name of the current window (a string). You can't shadow it in global scope via var, you have to use a scoping function or similar:

(function() {
    var name = [];
    for (var i = 0; i < 10; i++) {           // Note 1
        name[i] = prompt('Enter your name'); // Note 2
    }
    console.log(name);
})();

The lesson here: Avoid global scope. :-)

Note 1: You want < 10, not <= 10, if you only want 10 loops.

Note 2: You don't need to put () around the entire right-hand side of an assignment.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • _You can't shadow it in global scope via var_ But I could overlap it when I execute `var name = 1000;`, At the same time, I couldn't when I execute `var name = [];`. Can you explain it why? – Rajaprabhu Aravindasamy Dec 14 '16 at 10:03
  • @RajaprabhuAravindasamy: Because `name` is a string and its type cannot be changed. Assigning `1000` to it results in it being `"1000"` (the string), as though you'd assigned `String(1000)`. Assigning an empty array to it is like you assigned `String([])`, which is `[].toString()`, which is `[].join()`, which is `[].join(",")`, which is `""`. – T.J. Crowder Dec 14 '16 at 10:06
  • Totally understand. _Because name is a string and its type cannot be changed._ Is it so? Can't we change a type of a default property in window? – Rajaprabhu Aravindasamy Dec 14 '16 at 10:07
  • @RajaprabhuAravindasamy: It depends entirely on the property. `name`? No. Remember that `window` is a host-provided object. Host-provided objects can have non-JavaScript behavior (like fixed types). – T.J. Crowder Dec 14 '16 at 10:11
  • @T.J.Crowder Thanks a lot for your info. I read [this](http://stackoverflow.com/questions/7614317/what-is-the-difference-between-native-objects-and-host-objects) too, to get a clear understanding. – Rajaprabhu Aravindasamy Dec 14 '16 at 10:18
-1

Please try this code :

var nm = new Array(10);
for(var i =0; i<10; i++){
    nm[i]=prompt('Enter your name'); 
}
for(var i =0; i<10; i++){
   document.write(nm[i] + '<br>');
}

We can't use variable name as 'name'. As well to get array value we have to provide index number in array, so in above using for loop to get all values.

Thanks...