+ 16

Can you explain this code???

var a= []; for(var i=2;i>0;i--){ a[i]=i; } console.log(a.length*i) How the answer is 0. As a.length=3 and last value of i is 1 Why answer isn't 3???

3rd Aug 2020, 7:55 AM
TOLUENE
TOLUENE - avatar
9 Respuestas
+ 11
~ swim ~ Thank you. I generally don't understand for loops fully. Your answer makes all clear.
3rd Aug 2020, 8:22 AM
TOLUENE
TOLUENE - avatar
+ 9
🇧🇩🇳‌🇴‌🇷‌'🇼‌🇪‌🇸‌🇹‌🇪‌🇷‌ does it mean. inside loops last value of i is 1 and outside of it i becomes 0.
3rd Aug 2020, 8:08 AM
TOLUENE
TOLUENE - avatar
+ 8
~ swim ~ if last value of i is 0 Why a[0] is undefined ???
3rd Aug 2020, 8:10 AM
TOLUENE
TOLUENE - avatar
+ 3
The loop stops AFTER i becomes 0. So, 0. https://code.sololearn.com/W41h6b3WbOuA/?ref=app
3rd Aug 2020, 8:02 AM
Nor'wester 🌪️ 🇧🇩 (INACTIVE)
Nor'wester 🌪️ 🇧🇩 (INACTIVE) - avatar
+ 3
The last value of i is not 1 it is 0. See this to understand why it is 0. https://www.sololearn.com/learn/JavaScript/1140/
5th Aug 2020, 5:12 AM
MSN
MSN - avatar
+ 2
By tracing the code 1- a[2]=2. a[]= {null,null,2}; and the value of i will be decreased by one so i=1 2- a[1]= 1. a[] = { null,1,2} ; and the value of i will be decreased by one so i = 0 and this value won't meet the condition of the loop as the loop ask for i any value greater than 0 once it be 0 it won't meet the condition so the loop will be broken up and the last value of i is equal to 0 so by multiplying i by the a.length it will result in zero
3rd Aug 2020, 8:08 AM
ebrahem hesham
ebrahem hesham - avatar