why is undefined written here | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

why is undefined written here

var a="w3resource"; for(var i=a.length;i>=0;i--){ document.write(a[i]); } why is it printing undefined along with the word?

22nd Sep 2020, 10:38 AM
Ali Zain
Ali Zain - avatar
5 Answers
+ 4
Hi Ali Zain Try this var a="w3resource"; for(var i=a.length-1;i>-1;--i){ document.write(a[i]); }
22nd Sep 2020, 10:45 AM
Vachila64☕
Vachila64☕ - avatar
+ 2
The last index of a is not a.length, but a.length-1. a[i] doesn't exist thus undefined.
22nd Sep 2020, 10:45 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 2
var a="w3resource"; for(var i=a.length-1;i>=0;i--){ document.write(a[i]); } // I am just added a.length -1. 1.Now try this above code. 2. a.length is 10 but array index starts from 0 to 9. 3.first a[10] is going to print undefined.That's all.
22nd Sep 2020, 11:00 AM
Pon Balaji
Pon Balaji - avatar
0
Because we can't run this here .. Give the code please so we can run it
22nd Sep 2020, 10:44 AM
REO_LU
REO_LU - avatar
0
Got it! Thanks alot
22nd Sep 2020, 10:57 AM
Ali Zain
Ali Zain - avatar