i++ loops without any problem, i+2 loops infinitely and crashes - javascript

I want to create a simple loop function that adds 2 every time it loops. However, even though I tell my for loop to stop if the number reaches or is less than 100, it goes past 100 and loops infinitely.
i++ works just fine:
function addTwo() {
for (i = 0; i <= 100; i++) {
console.log(i);
}
}
addTwo();
When I change it to i+2 it crashes:
function addTwo() {
for (i = 0; i <= 100; i + 2) {
console.log(i);
}
}
addTwo();
I expect the console to log:
0
2
4
6
8
...
100.
But instead it loops infinitely and crashes.

i+2 in your case does nothing. JS evaluates it and then does nothing with the calculated value, this means that i is never increased.
++ is a special operator that increments the variable preceding it by 1.
To make the loop work you have to assign the value of the calculation i+2 to the variable i.
for (i=0; i<=100; i = i+2) {
console.log(i);
}
or
for (i=0; i<=100; i += 2) {
console.log(i);
}

i++ increments i. But, i+2 doesn't update the value of i. You should change it to i += 2
function addTwo() {
for (i = 0; i <= 100; i += 2) {
console.log(i);
}
}
addTwo();

The third parameter of a for is the final-expression:
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
In your case you are not assigning any value to i. You should replace it with something like this:
function addTwo() {
for (i=0; i<=100; i+=2) {
console.log(i);
}
}
addTwo();

i++ is a short hand for i += 1 which is called Increment Operator But i+2 or even i+1 will not increase the value of i. You need to increase it by assigning a new value to i. i = i + 2 or i += 2.
Number is one of the primitive types in javascript which mean you can't change it unless you use assignment operator =
Note: You are not using let or var with i this will make i a global variable.
function addTwo() {
for (let i = 0; i <= 100; i+=2) {
console.log(i);
}
}
addTwo();

for (i = 0; i <= 20; i++) {
console.log(i);
i++;
}
You can increase i twice Or
for (i=0; i<=100; i+=2) {
console.log(i);
}
you can use i+=2 it will increase value of i 2 times and set new value of i.

Related

Increment a variable by 3 in a loop that increments by 1

I want to create a loop where the "i" variable is incrementing by one (i++), and I want to add another variable "j" in the loop that increment not by one but 3 per 3 (so j+=3, and then the output looks like 0, 3, 6, 9, 12...).
I have tried so many thing, but here is my code that looks logic :
let j;
for (let i = 0; i < 24; i++) {
j = i += 3;
console.log(j); //It increments by 4, WTF ??
console.log(i); //Exactly the same whereas i should increments per 1
}
I also tried to create a variable "k" that is equal to "i" to leave "i" alone, but still doesn't work.
Thank you so much for your help guys :)
PS : Once solved, do you know how to make the variable j starts by 0 please ?
let j=0;
for (let i = 0; i < 24; i++) {
j+=3
console.log(j); //starts at 3, because in the first line of the function we say j = 0 + 3, so j=3, then once it loops again it gets +3 again, so it's 6 and so on.
console.log(i); //just increments by 1 each loop
Try this, is this what you were trying to achieve?
Like this - you can use comma separators in the initiator and loop statements in the for statement
for (let i = 0, j = 1; i < 24; i++, j += 3) {
console.log("i",i,"j",j);
}

Getting 'undefined', can't figure out why

Working my way through 'Eloquent Javascript' and I'm hitting a bit of a roadblock in understanding how to properly use if with for statements in the language. I'm supposed to write a function that counts all instances of the uppercase 'B' in a given string. The code I've written thus far:
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {}
counter += 1;
}
}
console.log(countBs("BBC"));
expected output: 2
actual output: undefined
Is my loop going wrong, or my 'if'?
You have two bugs
You are incrementing your counter outside of the if statement.
You have no return statement.
The following can be used:
function countBs(s){
var counter = 0;
for(i = 0; i < s.length; i++){
if ('B' == s.charAt(i)) {
counter += 1; // this needs to be inside the if statement
}
}
return counter;
}
Your function does not have a return statement.
A few issues.
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {
++counter;
}
}
return counter;
}
document.write(countBs("BBC"));
You were not returning counter at the end of the function
Your if statement was opened, then immediately closed, so nothing happens if the character was B
Even if you returned counter and fixed the above 2 errors, the function still would have exited after 1 B was found. To fix this, move the return after the for ends.
If you're interested, the same problem can be solved with this one-liner:
function countBs(s) {
return s.match(/B/g).length;
}
document.write(countBs("BBC"));
Which finds all B characters (case-sensitive), puts them into an array, then returns how many items are in that array.

When does this for loop escape?

To check my understanding, do we have that the following for loop never escapes only if row.length < n (otherwise, the loop can escape)?
function someFunction (matrix,n) {
for (var i = 0; i < n; i += 1) {
var row = matrix[i];
for (var i = 0; i < row.length; i += 1) {
if (row[i] < 0) {
alert("Something's wrong");
}
}
}
}
Do not use the same incrementing variable in nested for loops!
function someFunction(matrix,n) {
for (var i = 0; i < n; i += 1) {
var row = matrix[i];
for (var i = 0; i < row.length; i += 1) { //VERY BAD!!!
if (row[i] < 0) {
alert("Something's wrong");
}
}
}
}
When the inner loop completes the first loop, i will equal row.length. This will also complete the outer loop, which increments i again by 1. Thus, when the outer loop goes to begin its second iteration, you will have i=row.length+1. Do this instead:
function someFunction(matrix,n) {
for (var i = 0; i < n; i += 1) {
var row = matrix[i];
for (var j = 0; j < row.length; j += 1) { //using j instead of i
if (row[j] < 0) {
alert("Something's wrong");
}
}
}
}
It's bad practice to use the same loop counter i for the inner and outer loops. That's just confusing and leads to unpredictable behaviour.
But since you have done so and you want to know what will happen:
When the inner loop finishes for the first time, i will have the value of row.length from the first row in your matrix. i will then be incremented by the outer loop. If this new value of i is >= your n variable then the outer loop will end immediately. Otherwise the outerloop will continue with the new value of i and execute this line:
var row = matrix[i];
At that point if i is greater than or equal to matrix.length the row variable will be undefined, so then when you get to the inner loop and try to test row.length you are testing undefined.length which will give you an error and stop execution.
But if i is less than or equal to matrix.length then the inner loop would "work" in the sense of running again with the new value of row and with i set back to 0 for its first iteration.
If the previous row's length happened to be same as its index minus 1 then the same row would be processed over and over forever.
So essentially every iteration of the outer loop is selecting a more or less random (and possibly undefined) row to continue with based on whatever the length of the previous row was.

Javascript Averages

I am trying to learn Javascript. I've built the following code to find the average from an array of numbers. It works except the last returned value is always NaN. I cannot figure out why. If I move this piece outside of the block it seems to forget altogether what the variable sum is supposed to be equal to. Is there some kind of global-variable type equivalent I'm supposed to be using for JS?
var average = function(myarray) {
sum = 0;
for (counter = 0; counter <= myarray.length; counter++) {
sum = sum + myarray[counter];
average = sum / myarray.length;
console.log(average);
};
}
average([1, 2, 3])
Change
counter <= myarray.length
to
counter < myarray.length
because indexes start at 0.
Full example:
var average = function(myarray) {
var sum = 0;
for (var counter = 0; counter < myarray.length; counter++) {
sum += myarray[counter];
}
return sum / myarray.length;
}
console.log(average([1,2,3]));
JSBin Demo: http://jsbin.com/siyugi/1/edit
myarray[myarray.length] is undefined, which intoxicates your computation with NaN(Not A Number).
Just change it to
for(counter = 0; counter < myarray.length; counter ++) {
// ...
}
Since you are just learning you should know it is good practice to not use .length in a for loop like that. It causes the code to have to check the length of your array on each loop. And remember that .length is returning the number of elements in the array; but array index starts at 0.
for(var counter = 0, length = myarray.length; counter < length; counter++){
}
Would be the proper way to do it.
Don't use variables without declaring them with var keyword, otherwise they will become global properties.
The JavaScript Arrays are zero index based arrays. So, if the size of the array is 3, then the first element will be accessed with 0 and the last with 2. JavaScript is very forgiving, so when you access an element at an invalid index in the array, it will simply return undefined.
In the iteration, you are replacing the current function object with the average value. So, subsequent calls to average will fail, since average is not a function object any more.
It is a good practice to have a function return the computed value, instead of printing the value, so that it will not violate the Single Responsibility Principle.
In your case,
for (counter = 0; counter <= myarray.length; counter++) {
The counter runs till the last index of the array + 1. Since it returns undefined in the last iteration, JavaScript returns NaN in the arithmetic operation.
console.log(1 + undefined);
# NaN
So, you need to change the code, like this
function Average(myarray) {
var sum = 0, counter;
for (counter = 0; counter < myarray.length; counter++) {
sum = sum + myarray[counter];
}
return sum / myarray.length;
}
If you are interested, you can compute the sum with Array.prototype.forEach, like this
function Average(myarray) {
var sum = 0;
myarray.forEach(function(currentNumber) {
sum += currentNumber;
});
return sum / myarray.length;
}
Even better, you can calculate the sum with Array.prototype.reduce, like this
function Average(myarray) {
return myarray.reduce(function(sum, currentNumber) {
return sum + currentNumber;
}, 0) / myarray.length;
}
You can calculate the average of an array of numbers as follows:
var avg = c => c.reduce((a,b) => a +b) / c.length;
avg([1,2,3])

javascript closure in loop

Following code is given:
var a = [ ], i = 0, j = 0;
for (i = 0; i < 5; i += 1) {
(function(c) {
a.push(function () {
console.log(c); });
})(i);
};
for (j = 0; j < 5; j += 1) { a[j](); }
Why does i always get bigger by 1 instead of staying 5? Hasn't the foor loop already been passed, so the i parameter given to the anonymous function should be 5?
If you referenced i from the inner closure then yes, you would see the result being 5 in all cases. However, you pass i by value to the outer function, which is accepted as parameter c. The value of c is then fixed to whatever i was at the moment you created the inner closure.
Consider changing the log statement:
console.log("c:" + c + " i:" + i);
You should see c going from 0 to 4 (inclusive) and i being 5 in all cases.
chhowie's answer is absolutely right (and I upvoted it), but I wanted to show you one more thing to help understand it. Your inner function works similarly to a more explicit function call like this:
var a = [ ], i = 0, j = 0;
function pushFunc(array, c) {
array.push(function () {
console.log(c);
});
}
for (i = 0; i < 5; i += 1) {
pushFunc(array, i);
}
for (j = 0; j < 5; j += 1) { a[j](); }
Which should also help you understand how c comes from the function argument, not from the for loop. Your inner function is doing exactly the same thing as this, just without an externally declared named function.

Categories

Resources