I'm kinda new to Javascript and currently going over the book Professional Javascript for Web Developers and I came across this code which uses a break statement to exit the current loop and jump to a label named outermost.
Now I understand what break and labels do but I can't wrap my head around why the value ends up being 55 at the end?
Ok so the for loop with var i will loop 4 times then at 5 it breaks out to label:outermost and same with j so the first iteration i = 4 and j = 4 and num = 2. I guess this part confuses me.. at what point does the code stop. My first instinct if I were to code this from scratch is to have an outside variable and set the condition on that. But with the below code I don't get where the control structure lies and the final value. Appreciate any help or to be pointed in the right direction, thanks.
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
alert(num);
This nested loop is emulating an odometer. i is the 10's digit, j is the 1's digit. Every time the 1's digit changes, num is incremented; at the start of each iteration, num contains the odometer's value.
The loop stops when both i and j are 5. At that point, the odometer would read 55, and that's what is in num.
When i was 0 to 4, the innermost loop is executed 50 times. When i = 5, the innermost loop is executed just 5 times until it reached i==5 && j==5 and jumped out. So it's total of 55 times.
Related
I was playing with the break and continue keyword but I notice in chrome console this code doesn't work
for (let i = 0; i > 5; i++) {
console.log(i);
} //this will print all number from 1 to 5 but console showing undefined
However I tried changing i = 5 or i === 5 still it doesn't work
But when I changed it to i < 5 then it yields correct result.
Why is that?
your condition is i > 5. At the beginning i = 0 so it will not run ever.
put i < 5
Please check following diagram
Condition getting false on the first time so code block won't execute
i<5 indicates that the for loop will run as long as i is less than 5. i>5 indicates that 0 is less than 5 (let i = 0). So the correct program should be -
for (let i = 0; i <= 5; i++) {
console.log(i);
}
I have a assignment for a school project. The task is Write a for loop to log the message “I am love making pizza pies!” 10 times to the console.
Here's my code: I am using google Chrome as my browser
var pizza = '10'
for (var pizza = 0; < I.love.making.pizza; < pizza++) {
if (I.love.making.pizza;) {
pizza++;
}
}
console.log('I Love Making Pizza');
Step by step:
for (var i =0; i<10; i++){ // our loop.
console.log('I Love Making Pizza'); //our loop body
}
i is the variable we are iterating over. It starts at 0 (hence the var i =0 part). And after doing the loop body (the part between curly brackets) it gets increased by 1 (the i++ part which just means i=i+1). We do this as long as i is smaller than 10 (so until i is 9). Since from 0 to 9 there are 10 numbers we execute out loop body 10 times
Alternatively:
for (var i =1; i<=11; i=i+1){ // our loop.
console.log('I Love Making Pizza'); //our loop body
}
Now we go from 1 to 10 including 10 (hence the <=)
for(pizza = 0;pizza <= 10;pizza++){
console.log("I am love making pizza pies!");
}
The code above should do the trick.
i searched around for a couple of questions related to the use of the for loop and the setInterval function in JavaScript but i couldn´t find a concrete answer on why this snippet doesn´t work. Could someone explain please what´s happening under the hood and why this code doesn´t print anything at all?
for (let i = 0; i++; i < 10) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Your for loop is not correct. The condition needs to be the second statement in the for loop.
Following code should work.
for (let i = 0; i < 10 ; i++; ) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Expected Syntax for loop. You can read more here
for ([initialization]; [condition]; [final-expression])
statement
EDIT 1:
Though all answers (including mine) mentioned that condition needs to be second statement in the for loop which is correct. There is one more additional important behavior.
The for loop for (let i = 0; i++; i < 10) is actually correct in terms of grammar and even the javascript runtime executes this code.
But, as in your case, if the condition is evaluating to falsy value then it would exit the loop.
Breaking your for loop for (let i = 0; i++; i < 10) into each seperate construct
Initialization: let i = 0; This statement initializes the value of variable i to 0.
Condition: i++; Javascript evaluates the statement to check if the statement is true or not. In case of i++ the runtime firstly checks for the current value of i which is 0 . Since 0 is considered a falsy value the condition evaluates to false and hence the statement is not executed. Also, i++ statement is a post increment which basically increments i and then result the original value of i.
So, if you would have written loop like below, using the intiliaztion of i=1, then it would have worked, though it would be running infinitely untill the browser/Server crashes as the condition i++ would always evaluate to true. I hope that makes sense.
for (let i = 1; i++; i < 10) {
// Statements would run
}
Or
for (let i = 0; ++i; i < 10) { **// Pre increment**
// Statements would run
}
Or
for (let i = 0; i=i+1; i < 10) { **// increment i by assigment
// Statements would run
}
Douglas Crockford in his book Good Parts mention about the usage of ++ & -- and how it can confuse readers.
your for loop syntax is wrong, should be
for (let i = 0; i < 10; i++)
your setInterval code will run every 100 milliseconds for each iteration of the loop (so 10 times every 100 milliseconds)
Nothing to do with setInterval, you simply malformed your for loop:
This:
for (let i = 0; i++; i < 10)
Should be this:
for (let i = 0; i < 10; i++)
First declare the initial state of the loop, then the terminating state of the loop, then the incremental change of the loop.
Observe.
I am currently on Code Academy having fun learning. They have introduced push. and nested for loops pretty quickly without a lot of initial info. I THINK I understand the logic somewhat and would like to see if someone can help break it down...
var text = "Here is a string with the name rick sometimes not always rick and sometimes rick";
//assigning text string to variable text
var myName = "rick";
//assigning rick to variable myName
var hits = [];
// assinging an empty array to variable hits
for (var i = 0; i < text.length; i++); {
//for loop i = 0, and as long as i = less than the length of entire text string keep incrementing 1
if (text[i] === "r") {
//while looping through text when you find an "r" enter second for loop
for(var j = i; j < (i+ myName.length); j++){
//J takes the value of i at this point and it should be 0 and should increment 4 steps as myName = 4 characters
hits.push(text[j]);
//this push statement should add each letter of my name to the hits array
}
}
}
At this time my code does not work. I placed a console.log under the first for loop and it just prints 84.
"console.log("I= " +I)"
I understand this is pretty n00b but I really want to follow the logic and understand what is happening. Am I close?
You are really close.
You just have one problem:
The ";" after the for. It just goes to the end of the "for" loop doing nothing.
Take it out and it will work!!
Another thing you may like is to add to the list "hits" all the word that follows the 'r' character.
You should do:
if (text[i] === "r") {
var word = "";
for(var j = i; j < (i+ myName.length); j++) {
word+=text[j];
}
hits.push(word);
}
Also, be careful that i+myName.length is still in the limit of text.length (that is, i+myName.length < text.length)
Hope it helps!
Your code is pretty close. You accidentally put a semicolon after your first for loop:
for (var i = 0; i < text.length; i++);
This basically makes a 1 line block, same as this:
for (var i = 0; i < text.length; i++) {
}
Take that semicolon out and it should do what you want : ). although if your intent is to only push the ricks in then you need to check for more than just "r" you need to validate that each character after is also equal to rick.
You have a ";" after the for that should not be there. Also, you are still limited by the length of you string. So, you for statement becomes:
for(var j = i; j < (i + myName.length) && i < text.length; j++){
For example, if you had a string that was 82 characters long and you found an 'r' at the end of your text (i = 81), your original loop would set j to 81 and then try to check for characters in your string for indexes 82, 83, 84, and 85 which do not exist and would cause an error. Adding the addition check of i < text.length makes sure you do not try to check items that don't exists.
I don't know how far you are in your course. Just in case, the '&&' is an AND so j has to be less than (i + myName.length) AND also less than text.length.
Here is a JSFiddle of it working (http://jsfiddle.net/onlinespaces/xj39974c/1/)
Using JSFiddle is a great tool for things like this.
Good luck!
Can someone please tell me what's wrong with this code? Chrome and Firefox are saying that scrns[i] is undefined though Chrome still runs the code on mouseover.
function nextPrev() {
if (!document.getElementsByClassName) return false;
var scrns = document.getElementsByClassName('scrn');
for (var i=0; i<=scrns.length; i++) {
// console.log(i);
scrns[i].onmouseover = function() {
// console.log('foo');
}
}
}
window.onload = nextPrev();
I've tested that the for loop is working and tried to pin down where the problem is coming from in every way I know how. I'm even looking at an example I took from a book sometime ago and cannot understand why scrns[i] would be undefined.
Any help greatly appreciated!
You're using <= when looping through. But remember that arrays are indexed starting at 0, not 1. So an array with 10 elements has a length of 10, but elements 0-9. Change the following:
for (var i=0; i<=scrns.length; i++) {
to:
for (var i=0; i < scrns.length; i++) {
You are looping too far. If i is equal to scrns.length then it is beyond the end of the array. Remove the = in your stop condition:
for (var i=0; i < scrns.length; i++) {
You have an off by one error. Changing <= to < should fix your issue. You can use loop invariants in the future to make sure that you don't go over.
http://en.wikipedia.org/wiki/Loop_invariant
In general though, when looping through an array, begin with the iterating counter at 0 and then loop so long as the counter is less than the length of the array.