javascript what is wrong with this "for" loop syntax? - javascript

Can someone please help me?
I am currently learning Javascript, and I don't understand what's wrong with the following piece of code:
var names = ["vasco", "joão", "francisco", "rita", "manuel"];
for (var i = 0; i < 4; i++); {
console.log("I know someone called " + names[i] + ".");
}

Arrays in JavaScript are zero-indexed. That means the element in the very first position is at index 0. To target that element, you can refer to it like names[0]. In your loop, you are iterating while i < 4, meaning once i becomes 4, the loop stops and does not continue. So you are only calling console.log 4 times. A common practice when iterating through an array is to say i < names.length. Also there are a couple syntax errors as others have pointed out. Below is a working version.
for (var i=0; i < names.length; i++) {
console.log ("I know someone called"+" "+names[i]+".");
}

because you terminate the for loop by semicolon(;) ,so for loop is seperated by its block .
then,
Ques1. what'll do next when code is run?
Ans. when execution comes to for loop, loop executes untill the value of i goes to 4 . then , the next block statement is executed.
Ques2. Why "manuel" is print in o/p?
Ans. answer is simple ,because foor loop terminates when value of i goes to 4 , so
console.log("I know someone called " + names[i] + "."); //it prints the arr[4]

You have ; at the end of your for, just remove it

Please remove the semicolon after the for to be:
var names=["vasco","joão","francisco","rita","manuel"];
for ( var i=0; i <5 ; i ++) {
console.log ("I know someone called"+" "+names[i]+".");
}
also the condition i<4 is the stopping the last case

there are two issues with the code you wrote ,
1- you have a semi-colon after the condition for(condition);
which result in the loop not doing anything
2- you are off by one, last element of the array has index 4
condition should be (i <= 4) or (i < array.length)
var names = ["vasco", "joão", "francisco", "rita", "manuel"];
for (var i = 0; i < names.length; i++){
console.log("I know someone called " + names[i] + ".");
}

Related

What does this code means? (Javascript FOR loop) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Can someone explain this code to me?
Any help will be appreciated ! Thanks!!
<p id="arrayString"></p>
<script type="text/javascript">
var arrayString = "";
var myArray = ["pizza", "hamburger", "chicken leg"];
for (var i = 0; i < myArray.length; i++){
arrayString = arrayString + myArray[i] + " ";
}
document.getElementById("arrayString").innerHTML = arrayString;
</script>
</body>
Here is the code with some comment:
<p id="arrayString"></p>
<script type="text/javascript">
var arrayString = ""; //store an empty string in the variable (the purpose is to initialize the variable in wich after(for loop) we will store the names)
var myArray = ["pizza", "hamburger", "chicken leg"]; //create an array with some string elements
//foreach element in the array (the strings)...
for (var i = 0; i < myArray.length; i++){
//...add the 'i-est' element of the array to the string variable 'arrayString' and insert a space after the element
arrayString = arrayString + myArray[i] + " ";
}
//print the string in the html element with id 'arrayString'
document.getElementById("arrayString").innerHTML = arrayString;
</script>
</body>
The for statement iterates over the elements of the array, and in each iteration you access an element with: myArray[i]
Check here to see how the for loop works
I'm assuming you mean the for loop and not the other stuff.
for loops are basically while except more organized. for(var i = 0; is making the variable that is going to determine when to end the for loop.
i < myArray.length; is basically while(i < myArray.length) aka while i is less than myArray length it will do what's inside.
lastly, i++; tells the for loop what to do to i at the end of the statement to eventually make it >= to myArray.length.
The for loop creates a variable i and executes the code within the loop as long as i is less than the length of myArray. Each time the code in the loop is executed, i is increased by 1.
for (var i = 0; i < myArray.length; i++) {
arrayString = arrayString + myArray[i] + " ";
}
is saying for the variable i, if i < myArray.length, execute the code arrayString = arrayString + myArray[i] + " "; which adds the ith element of myArray to arrayString. For example, when the loop starts, i=0. So if it is true that i < myArray.length, then the 0th, or first, element of myArray is added to arrayString (Since array indexing begins at 0: 0 is the first element, 1 is the second, 2 is third, and so on. Then, once that is finished, the flow of control jumps back into the conditions in the for loop and executes i++, or "increase i by one". This whole process continues until the statement i < myArray.length is false (meaning i >= myArray.length, in which case the code in the for loop will be trying to add elements of the array that do not exist, like "add the 6th element of a 5 item long list").
The last line,
document.getElementById("arrayString").innerHTML = arrayString;
gets the element in the document with the id "arrayString" and displays the text contained in arrayString in that element (which is the one defined at the top in paragraph tags).
It's converting an array into a string. You could just use this, though:
document.getElementById("arrayString").innerHTML = myArray.join(' ');

Javascript stuck at "for" loop

i am newbie learner and i am learning basic javaScript from codecademy.I stuck at "Search Text for Your Name" tutorial 5/7.
here is my question:
your loop should stop when it hits the value of the first iterator (say, i)
plus the length of your myName variable.
here is some informations from to tutorial:
Your second "for" loop
Okay! Last loopy step: add another for loop, this time inside the body of your if statement (between the if's {}s).
This loop will make sure each character of your name gets pushed to the final array. The if statement says: "If we find the first letter of the name, start the second for loop!" This loop says: "I'm going to add characters to the array until I hit the length of the user's name." So if your name is 11 letters long, your loop should add 11 characters to hits if it ever sees the first letter of myName in text.
For your second for loop, keep the following in mind:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
> for(var i = 0; // rest of loop setup
your second should be something like
> for(var j = i; // rest of loop setup Second
think hard about when your loop should stop.
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
and here is my code:
multistr:true
var text = "Hey, how are you \
doing? My name is Emily.";
var myName = "Emily";
var hits = [];
for (var i = 0; i > text.length; i++)
{
if (text[i] === 'E')
{
for(var j = i; j > text.length; j++){
};
};
};
ps: i don't want to pass this tutorial without understand it. please help me. teach me.
for (var i = 0; i > text.length; i++) should be
for (var i = 0; i < text.length; i++)
otherwise it won't ever meet the criteria to even start the loop.
Welcome on board! You confused > with <. Your loops won't run because for the first check when i = 0 it certainly does not hold that 0 > text.length, because text.length is at least 0 (there are no strings shorter than the empty string).
You should make a habit of manually going through your loops for the first two steps and then check what happens just before the loop ends.
Here is what I got for my code:
for ( i = 0; i < text.length; i++)
{
if ( text[i] === "E")
{
for( var j = i; j < (myName.length + i ); j++)
{
hits.push(text[j]);
}
}
};
It looks like you were missing the " + i " part in your second for loop. That seems to make sure that the first loop will be included. I tried it without the "+ i" and it does not work.
I tried continuing directly from the second for loop using a "+ j" and that only crashes the browser.

Closure in JavaScript from CoderSchool

I was doing some studying on CodeSchool. While watching a tutorial I was confused by an example. What they were trying to explain in the video was that closures created in loops won't bind until the last minute. The aim for this code was to take a name check for it in the array and return the name alone with its position(without the zero convention). Since closures don't bind till the last minute this code is returning z 5. I am confused why this code is returning a 5 and not a 4. The length of my array is 4 and the for loop stops before 4 because i < passengerArray.length which is the equivalent of i < 4 therefore the last index checked should be passengerArray[3] which means my (i+1) should be 4 in the end and not 5. I hope that makes sense. This has been bothering me all day.
function assignTorpedo(name, passengerArray)
{var torpedoassignment;
for(var i = 0; i < passengerArray.length; i++){
if(passengerArray[i] == name){
torpedoAssignment = function(){
console.log(name + " " + (i+1));
};
}
}
return torpedoAssignment;
}
var give = assignTorpedo("z",["z","a","b","c"]);
give();
The for loop ends when the test condition fails. Why does it fail? Because i is not less than 4; it's equal to 4. Thus, in the console.log() output you see 5.
Also, the statement
closures created in loops won't bind until the last minute.
is a strange way of describing how things work. As soon as the name is found in the array, the variable is assigned a reference to the constructed function. When assignTorpedo returns that value, the closure exists. In the closure, the value of the variable "i" is already 4.
The following statement increments i by 1 after each pass through the loop. So, after the fourth iteration i will be increased by one and tested against the condition again, and then it will fail.
var arr = ["z","a","b","c"];
for ( var i = 0; i < arr.length; i++ ) {
console.log( i );
}
console.log( i );
The For loop finishes when condition "i < passengerArray.length" being violated which i equals 4 at that time.
then console.log(name + " " + (4 + 1)));
Power Tip:
From one of my lecturers in uni,
"Think a "For" loop like a 'While' loop like this"
i = 0;
while (i < passengerArray.length)
{
...............
i++;
}

Why doesen't prompt() inside a for loop in javascript work for my code below?

Why doesen't prompt() inside a for loop in javascript work for my code below?
var P = [];
for(i=0;i++;i<10)
{
var g=parseInt(prompt("What is the money you paid in"+i+ "month?"));
P[i]=g;
}
Your for loop is wrong. It should be
for (i=0;i<10;i++)
You mixed up the second and third parts. The condition comes second, the variable increment comes last.
You swapped the parts of the for loop. The condition is second:
for(var i = 0; i < 10; i++) {
Also don't forget var, and parseInt(x, 10) prevents some weird behaviour.
Your loop is formatted incorrectly, a for loop should be:
for ( state; condition; action )
So, given your case, the correct loop is:
for (var i = 0; i < 10; i++)

Attempt to add values to Array causes app to spin into an endless loop

for some sick reason, my check productIDs[addIndex] = allProductIDs[lastProductFoundIndex + i]; causes my app to spin into an infinite loop:
numberOfImagesToDisplay is set to 4
if (state == "next")
{
for(var a = 0; a < numberOfImagesToDisplay; a++) {
alert("a=" + a + ", numImages=" + numberOfImagesToDisplay)
if (a > 0) { addIndex = productIDs.length + 1; }
alert("I'm in GetNextProductIDs() 1");
//var lastProductFoundIndex = $.inArray(lastProductID, allProductIDs);
//alert("I'm in GetNextProductIDs() 2");
if (lastProductIndex >= 0) {
alert("I'm in GetNextProductIDs() 3");
//productIDs[addIndex] = allProductIDs[lastProductFoundIndex + i];
}
}
}
If I take out that line, it moves on.
Update: Resolved. lastProductIndex was not defined. So what was happening is that it would get there and the loop would end but it's weird because a callback was being called again when it should have ended. So that callback method kept calling this method and this method would end at that spot, the callback method would again be called, and so you had an endless loop.
That's very strange. All I can think is that you have an onpropertychange event firing that also modifies i. Major longshot, I know.
What if you add the var keyword to your for loop? That would turn it into a local variable instead of a global variable so no other function could inadvertantly trash your loop index.
for (var i = 0; i < numberOfImagesToDisplay; i++)
Note: You should have the var there whether or not that's the problem.
Update: What does alert("i="+i+", numImages="+numberOfImagesToDisplay) display each iteration through your loop? Do those variables have the expected values?
Are you sure this loop is stuck? Maybe it's another loop. Could it be that you're re-entering this loop repeatedly thereby getting repeated alerts? I just don't see how that line could cause this loop to become an infinite loop.
I don't see you incrementing variable a in there anywhere, but you're incrementing a variable i in your loop. a will therefore always be 0 -
for(var a = 0; a < numberOfImagesToDisplay; i++)
It's not related to your suspected problem line, but, at the line
for(var a = 0; a < numberOfImagesToDisplay; i++)
your setting a = 0 and the loop will run while a < numberOfImagesToDisplay. I dont see anywhere where you are incrementing or changing a to exit the for loop.

Categories