Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  154] [ 7]  / answers: 1 / hits: 46259  / 11 Years ago, thu, april 18, 2013, 12:00:00

I came across a problem which I did manage to solve but I honestly do not understand how this works.



var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
//My code
for (var i = 0; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}

console.log(largest);


How does my array assign a value to my variable within the if statement?



Why does this version not work?



array[i] = largest;


I'm very new to programming and I believe that understanding fundamental things as small as this can help many beginners become competent programmers.


More From » arrays

 Answers
35
if(array[i] > largest) {
largest = array[i];
}


array[i] is 3 and largest is 0 then if condition passes and



largest = array[i];


assign value right to left
now the largest value is 3.



so next cycle array[i] is 6 so next 6 > 3 true , it will again change the largest to 6.



like it will give you largest number.


[#78807] Wednesday, April 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alanisannettep

Total Points: 695
Total Questions: 96
Total Answers: 91

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
;