What does "for" does in this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What does "for" does in this code?

function a(){ var pm = "" var str = "HI"; for(var i = 0; i<str.length; i++){ if(str[i] == "H"){ pm += "h" } else if(str[i] == "I"){ pm += "i" } } document.write(pm) } a()

4th Jul 2018, 8:54 AM
Sina
Sina - avatar
7 Answers
+ 4
No, that's not what I meant, okay let's review the code ... var count = 0 // first "if" 'count' value is still zero ... if(str[count++] == "H") // this is true, because str[0] == "H" // the second "if" sees that 'count' value is now 1 (incremented) so when we check ... if(str[count++] == "I") // this is true, because str[1] == "I" BUT if we use else...if ... count = 0 if(str[count++] == "H") { // this block is executed, because str[0] == "H" } else if(str[count++] == "I") { // the else..if block is not executed, because str[0] not equals "I" ... } I hope it's clear enough, come ask again if you still unsure ...
4th Jul 2018, 1:22 PM
Ipang
+ 4
The first code uses loop to iterate the <str> and concatenate a lowercase "H" or "I" into <pm> when one was found in <str>. The second code only adds "h" to pm variable because the part that checks for "I" is in the else..if block. If you want the same output, change it to if(str[count++] == "I") This will check the second character in <str> and adds "i" into <pm>. Hth, cmiiw
4th Jul 2018, 10:11 AM
Ipang
+ 4
Sina it was because the else...if block is supposed to be executed when the "if" part sees that str[count++] value does not equal to "H", when the "if" part is evaluated, the 'count' variable value was still zero (due to post increment operator), and the character at index zero was "H". The second "if" however, sees that 'count' variable value has been incremented to 1, and the character at index 1 is "I", so the evaluation yields true, then the "i" character is added to 'pm' variable. Hth, cmiiw
4th Jul 2018, 1:09 PM
Ipang
+ 1
Why when I change it to "if" it works but when it's "else if" it doesn't work
4th Jul 2018, 12:47 PM
Sina
Sina - avatar
+ 1
you mean when we use if the countstart from zero agin yes??
4th Jul 2018, 1:11 PM
Sina
Sina - avatar
0
and what is diffrent between this and that var count = 0; function a(){ var str = "HI"; var pm = ""; if(str[count++] == "H"){ pm += "h" } else if(str[count++] == "I"){ pm += "i" } document.write(pm) } setInterval(a)
4th Jul 2018, 9:00 AM
Sina
Sina - avatar
0
Ok underestood thanks a lot
4th Jul 2018, 5:52 PM
Sina
Sina - avatar