trivial for-loop needs an explanation - javascript

Since i += i is an abbreviation for i = i + i, the following code
for (var i = 0; i<=10; i++) {
console.log(i += i) }
should output:
1. 0, because 0 += 0 + 0 (i = 0)
2. 2, because 0 += 1 + 1 (i = 2)
3. 6, because 2 += 2 + 2 (i = 6)
4. 12, because 6 += 3 + 3 (i = 12)
However, although the console does output the values of 1. - 3., namely, 0, 2, and 6, correctly, the value that I get for 4., which is 14, is not the value that I predicted (the lines 1. - 4. above were typed out before the for-loop was executed) the for-loop would output (=12).
What am I interpreting wrong here?
The code itself is evidently uninteresting, but nonetheless I am curious why it works the way it does.

So basically, you are adding one then double the number in each iteration, starting with 0.
Then you should get: 0, 2, 6, 14. I think your math, not code, is wrong here.

Recall that for loops have four parts: Initialiation, Test, Body, and Increment.
...and they work like this:
Initialization
Test, jump to after loop if test is false*
Body
Increment
Go to step 2
So, here's the way that loop works:
(Initialization) i = 0
(Test) Since 0 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 0, i = 0 + 0 is i = 0.
Log that
(Increment) Evaluate i++. Since i is 0, it becomes 1
(Test) Since 1 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 1, i = 1 + 1 is i = 2
Log that
(Increment) Evaluate i++. Since i is 2, it becomes 3
(Test) Since 3 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 3, i = 3 + 3 is i = 6
Log that
(Increment) Evaluate i++. Since i is 6, it becomes 7
(Test) Since 7 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 7, i = 7 + 7 is i = 14
Log that
(Test) Since 14 is not <= 10, stop
* "Test, jump to after loop if test is false" Technically, not just false, but anything falsey, which is 0, null, undefined, NaN, "", or of course, false.

The problem is that you are updating i inside the loop as well as for the loop itself. This means you need to look at both updates to see what really happens to i. Here are the steps unrolled:
for(var i=0; i<=10; i++){ ...
// i = 0 here
console.log(i += i);
// logged 0 += 0 (0)
// now i will be incremented to 1
console.log(i += i);
// logged 1 += 1 (2)
// increment i to 3
console.log(i += i);
// logged 3 += 3 (6)
// increment i to 7
console.log(i += i);
// logged 7 += 7 (14)
// increment i to 15
// ... etc
It looks like you just missed the fact that += is also updating the i inside the loop, not just from the ++ incrementor.

This is what your code does:
1. i starts with 0, then you assign to it 0 + 0. console logs i as 0
2. i increments to 1, then you assign to it 1 + 1. console logs i as 2
3. i increments to 3, then you assign to it 3 + 3. console logs i as 6
4. i increments to 7, then you assign to it 7 + 7. console logs i as 14
Note that i += i is not the same as i += i + i, but as i = i + i. It is an assignment, and the value returned is the new value of i.

Related

Can someone explain this simple concept of a JavaScript loop?

Considering this code:
var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
println(x);
Why would the output be 6? Can someone break it down for me?
I understand that x will continue adding 1 to it's value, but why does the i<3 limit it to 6?
The answer will be 6 because your initial value of X is 3.
You have only 3 iterations in your while loop.
i = 0 => x +1 = 4
i = 1 => x + 1 = 5
i = 2 => x + 1 = 6
i = 3 => exit loop
I will explain it step by step
while loop will take values, while i is smaller than 3 right.
X starts as 3 and i starts as 0.
While checks if i < 3. (it is 0 for now )
(x+=1 means x = x + 1 (same for i ))
i was 0, so while loop will start working.
x will become 4 and i will become 1.
second run: i is 1 still lower than 3 so while loop will keep working.
x will become 5 and i will become 2
i is still lower than 3 so while loop will keep working
x will become 6 and i will become 3
now i is equal to 3 so no longer lower than 3. While loop will stop working and you will get the outputs.
But if console.log (x) was in the while loop. You will get all the x results.
The output would be:
4
5
6
So, if your question is why am I getting only 6 as an output? It is because your function comes after the while loop.
Before entering into the loop: x=3, i=0 (i is less than 3, so the condition is true)
After the first step: x=4, i=1 (i is less than 3, so the condition is true)
After the second step: x=5, i=2 (i is less than 3, so the condition is true)
After the third step: x=6, i=3 (i is not less than 3, so the condition is false)
Because the condition is false, it is exited from the loop and the value of x is printed in the output.
Also, println() is not defined in JavaScript. We can use console.log().
The code of
var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
increments x and i repeatedly. Initially, i is 0, which is important, as its incrementation's result determines whether the loop should continue. Since the loop criteria is that i < 3 is (still) true, starting from 0 and adding 1 to the value of i, your loop's block will be executed 3 times (it's executed for i=0, then it's executed for i=1 and then it's executed for i=2 and finally, for i=3 it's not executed, because the condition of i < 3 is no longer true when i=3).
Since the loop block is executed 3 times and both i and x is incremented by 1 at each execution, their value increases by the same value during the process. Since i was increased by 1 a total of three times, its value was changed from 0 to 3 (0 + 1 + 1 + 1 = 3). Since the initial value of x was 3, it changed from 3 to 6 (3 + 1 + 1 + 1 = 6).

Unexpected result of increments sum

Good afternoon, please explain why, when waiting for 3, 4 is output to the console.
let x = 1;
console.log (x++ + ++x) // 4
At first, I thought that the priority of operations, but then why in such an example outputs 8, and not 6 for example?
let x = 1;
console.log (x++ + ++x + ++x) // 8
Sorry, if this question is duplicated, but I can't find any about this question.
For the first example:
let x = 1;
console.log (x++ + ++x) // 4
x++ returns the value of x (1) and increments it afterward. x is now 2. (This is postfix increment.)
++x increments the value of x and returns it, which is 3 (2 + 1). (This is prefix increment.)
1 + 3 = 4
See Increment Operator.
x++ or x-- is first use then update.
++x or --x is first update then use.
update means update the value of the variable x.

is ++ = +1 in JavaScript?

Why when I use the following codes in JS it works properly ?:
let counter = 5;
while (counter < 10) {
console.log(counter);
counter ++;
}
But when I try the following codes it doesn't?
let counter = 5;
while (counter < 10) {
console.log(counter);
counter + 1;
}
You're missing an assignment there.
counter++ directly increases the counter itself by one.
counter + 1 just returns the value of counter plus one.
Solutions might be:
counter += 1;
counter = counter + 1;
This happens because on the second example, you are summing 1 to counter value, but it's not using this sum to nothing.
Let me exemplify:
let c = 0;
console.log(c + 1); // outputs 1
console.log(c); outputs 0, since in the last statement you didn't changed the original value, just used it.
console.log(c++); // will output c then increment c. So it prints the old value: 0
console log(c); will output 1 (result of previous increment)
console.log(++c); // will increment c and then output it new value: 2
Keep in mind that
c++;
Is the same that:
c = c + 1
The increment operator will increment a value and return a value that differs depending on whether it is used in a prefix or postfix position.
In postfix position it returns the original value:
let x = 0
console.log(x++) // 0 (!!)
console.log(x) // 1
In prefix position it returns the new value:
let x = 0
console.log(++x) // 1
console.log(x) // 1
You can type it out long hand if you want, using the addition and assignment operators separately:
let x = 0
console.log(x = x + 1) // 1
console.log(x) // 1
There is another operator too: the addition assignment operator:
let x = 0
console.log(x += 1) // 1
console.log(x) // 1

ignoring of operations outside of brackets

var x = 0;
var arr = [4,9,2];
arr[x] = (++x)-1;
document.write(arr[x]);//9
//Why js ignores minus that outside of brackets? Why is it 9 not 4?
This (++x)-1 would result in 0 and the x would be 1 after the evaluation of this statement, since you have incremented it by 1 and it was assigned the value of 0.
So this arr[x] (in the statement document.write(arr[x]);) is actually arr[1] and arr[1] is assigned the value of 9.
Regarding the assignment:
arr[x] = (++x)-1;
Now the value of the first element of the array (with index 0) would be assigned the value 0. This is why if you print the arr you will get the following output:
[0,9,2]
you write to
arr[x] // which is arr[0]
(++x)-1; // 1-1 = 0, x = 1
then you write out
document.write(arr[x]); //arr[1] which is 9
Why js ignores minus that outside of brackets?
so no, js does not ignore the minus. Maybe try to understand the prefix ++ operator wtthout using arrays, since they confused you a bit in this case.
Example:
var x = 0, y = 0;
y = (++x) - 1;
document.write("x: " +x + " y: " y); //x == 1, y == 0
Basically this with prefix increment
++x - 1
is the same as the use of x with a postfix increment.
x++
arr[0] = 0, here x incremented by 1 so, x = 1, (1)-1 = 0
arr[1] will print 9 because x = 1 , you are accessing the array
element with index 1
document.write(arr) it will print [0,9,2] ,because the first
element of the array (with index 0) would be assigned the value 0.
var x = 0;
var arr = [4,9,2];
arr[x] = (++x)-1;
// x would be 1 after the evaluation of this statement.
//document.write(x);// it will print 1
document.write(arr[x]);// arr[1] it will print 9
//document.write(arr);// it will print [0,9,2]

javascript empty loop body

I'm working through eloquent javascript and I don't understand this bit of code
for (var current = 20; current % 7 != 0; current++)
;
console.log(current);
It states that it checks for the first number greater than 20 that is divisible by 7 and console.log() would produce 21.
But I read that as start at 20, check if current divided by 7 has no remainder to see when we break the loop. But straight away 20 mod 7 == 6 meaning it does not equal 0 or (20 % 7 != 0).
So shouldn't the for loop break straight away and console.log(current) produce 20? What am I missing here?
A loop continues as long as the condition is met.
20 % 7 != 0 // 6 != 0 is true, so condition is met and loop continues
21 % 7 != 0 // 0 != 0 is false, so condition fails and loop halts
"... check if current divided by 7 has no remainder"
No, it's "check if current divided by 7 does NOT have no remainder".
I think the negative condition is throwing you. Basically, you need to ask if the condition is a true statement.
So if I'm the condition, and you're the loop, and I say "six does not equal zero", you would say "that's true", so you would agree to let the loop continue.
But then if I say "zero does not equal zero", you would say "that's false", and would halt the loop.
A clearer condition would be "check if current divided by 7 does have a remainder". No double negative, so it could be written as:
for (var current = 20; current % 7; current++) ;
or as:
for (var current = 20; current % 7 > 0; current++) ;
Nothing is wrong here. Simply change the ; line to this line, and you'll get the idea:
for (var current = 20; current % 7 != 0; current++) {
console.log('current value is ' + current ' +
' and the mod result is ' + current % 7);
}

Categories