++i vs i++ in javascript confusing function - javascript

What would be the difference between
var nums = [];
for (var i = 0; i < 10; ++i) {
nums[i] = i+1;
}
and
var nums = [];
for (var i = 0; i < 10; i++) {
nums[i] = i+1;
}
In the for loop, i = 0, but in the first iteration, would nums[i] = nums [0] or nums [1] since we are using ++i? How would the first iteration be different if i++ were used instead?
Update: For this particular for loop it doesn't matter. However, I'm interested to see a for loop where ++i vs i++ matters.

They would be exactly the same; ++i and i++ have the same effect on i, but the value of each expression is different; in this context, since the value is ignored, the code behaves the same.
As an example where switching between the two would matter, here is some truly awful code:
for ( var i=0; i++ < 10; )

++i increments before the "return", i++ increments after
var i = 0;
i++; //=> 0
i; //=> 1
var j = 0;
++j; //=> 1
j; //=> 1
For the purposes of your for loop, it doesn't make a difference.

In for loops, there is no difference. The difference between ++i and i++ is the value returned by the expression, but the expression is evaluated after each pass of the loop and you ignore the value.

There is no difference between the two. The incremented value will be ignoreed as it will happen at the end of the loop.
EDIT:
It makes no difference in the for loop if you write
for (var i = 0; i < 10; ++i) {
or
for (var i = 0; i < 10; i++) {
You will get the same results in both the cases. The reason why most of the people use i++ or better to say why i++ is more popular over ++i in a for loop is probably because people come from a habit of using i++ which was majorly used in C. Also to note that in C++ you can write your own version of ++ operator.

They are the same. The increment occurs at the end of the body of the loop.
i.e. you can view the loop as
var i = 0;
while (i < 10) {
... Body of loop
i++ or ++i;
}

Related

Complexity of nested for loops starting from the last iteration

function solution(A) {
var len = A.length;
cnt = 0;
for(i = 0; i < len - 1; i++){
for (a = i + 1; a < len; a++){
if (A[i] == A[a]){cnt++;}
else{continue;}
}
if(cnt > 1000000000){return 1000000000;}
}
return cnt;
}
So this is a code for counting identical pairs of an array, I know that 2 for loops give time complexity of O(n2). Is it always the case? Even if the next iteration goes through only remaining part of the array?
Yes this will be roughly O(1/2n^2) but since constants aren't really that important this will end up being O(n^2)

Buggy Javascript Function Complains Missing For Loop ")"

The following is my simple function to create a range array between two numbers. The problem is that console keeps complaining that for loop has a missing bracket ")" but I can plainly see that it is not missing. Please help!
function range(start, end){
var len = end - start;
for (var i = 0; i <= len; i++){
var arr[i] = x + i;
}
return arr[];
}
console.log(range(1, 10));
console.log(arr.length);
Here is the output:
SyntaxError: missing ) after for-loop control (line 3)
Edit
for (var i = 0; i <= len; i++){
was
for (var i = 0; i <= len; i++;){
remove
↓
for (var i = 0; i <= len; i++;)
Remove the final semicolon:
for (var i = 0; i <= len; i++)
Your code has other issues, but this answers the question asked. I suggest you pull out a guide on JavaScript and correct your syntax throughout your code.
There were three errors. I cannot fix undeclared 'x', which is either in outter scope (global) or this is an error that you have to fix with your own logic.
function range(start, end){
var arr = []; //declare your array
var len = end - start;
for (var i = 0; i <= len; i++){
arr[i] = x + i; //here x is undeclared, single array indices cannot be declared this way
}
return arr;
}
console.log(range(1, 10));
console.log(arr.length);
You shouldn't put a semi-colon (;) after the last statment in the for loop. Remove it.
It's very unlikely that something like a for loop is buggy in JavaScript, in a language that is usef by millions every day.

let vs var performance in nodejs and chrome

When I test following code in chrome and nodejs, I get following:
Chrome:
for loop with VAR: 24.058ms
for loop with LET: 8.402ms
NodeJS:
for loop with VAR: 4.329ms
for loop with LET: 8.727ms
As per my understanding, because of block scoping LET is faster in chrome. But can someone help me understand why is it opposite in NodeJS?
Or am i missing something?
"use strict";
console.time("for loop with VAR");
for (var i = 0; i < 1000000; i += 1) {
// Do nothing
}
console.timeEnd("for loop with VAR");
console.time("for loop with LET");
for (let i = 0; i < 1000000; i += 1) {
// Do nothing
}
console.timeEnd("for loop with LET");`
PS: Not sure if this is not the ideal way to test performance.
V8 version shipped with node.js 5.10 don't support the temporal dead zone for let bindings.
Chrome instead is using V8 5.0 that support it...but as the vm is not yet optimized to handle TDZ, is normal that for now it's slower (I remember reading people who assert that replacing var with let made the code about 27% slower).
When you do
for (let i = 0; i < 1000000; i += 1) { }
the i value in each loop cycle is a separate reference, which is useful when using the i value in an asynchronous callback. This is slower, but can be faster than alternatives in this usage case.
When instead you use
let j;
for (j = 0; j < 1000000; ++j) { }
you will only have one value reference, and it will be just as fast as with var.
Try the following code
console.time("let i");
for (let i = 0; i < 10000000; ++i) { }
console.timeEnd("let i");
console.time("let j");
let j;
for (j = 0; j < 10000000; ++j) { }
console.timeEnd("let j");
console.time("var k");
for (var k = 0; k < 10000000; ++k) { }
console.timeEnd("var k");
this will give results like
let i: 91ms
let j: 25ms
var k: 27ms
where clearly let is equally fast to var when used correctly.
Also to see the difference in asynchronous behaviour, try
for (let i = 0; i < 3; ++i) {
setImmediate(() => { console.log(i) });
}
let j;
for (j = 0; j < 3; ++j) {
setImmediate(() => { console.log(j) });
}
for (var k = 0; k < 3; ++k) {
setImmediate(() => { console.log(k) });
}
which will output
0
1
2
3
3
3
3
3
3
as in each cycle of the loop for let i the i value is a unique reference, which is what causes the slight overhead, whereas for the other two loops it's the same reference.
i can't tell you more but as mentiont in this video (very good), you need smarter code to test this.
https://www.youtube.com/watch?v=65-RbBwZQdU
the compiler will to magic stuff with your code and might even ereas the loop if you don't use i and the loop is empty

Javascript - How does "++i" work?

After experimenting with the use of "i++" and "++i" I could not find a difference between their results when used in a 'for' loop.
For example:
for (var i = 0; i < 10; ++i) {
console.log(i);
}
would yield:
0
1
2
3
4
5
6
7
8
9
Shouldn't it be printing out the numbers from 1 to 10, as the iterator is being incremented before console.log(i) executes?
The "increment step" is executed after the loop body is executed. Given
for (a;b;c) {
d
}
the execution order is
a // initialize
b // condition - first iteration
d // loop body
c // "increment"
b // condition - second iteration
d // loop body
c // "increment"
...
b // condition - last iteration - break
So in your case:
var i = 0;
i < 10;
console.log(i); // 0
++i;
i < 10;
console.log(i); // 1
++i;
// ...
i < 10;
The difference between i++ and ++i is only relevant if you do something with the return value, which you don't.
Because the last clause of the for loop only happens at the end of the loop, as its own statement, the behavior of your loop is not affected by this difference. However, imagine you did something like this:
for (var i = 0; i < 10;) {
console.log(++i);
}
for (var j = 0; j < 10;) {
console.log(j++);
}
Then you'd see a difference. The first example would produce numbers 1-10, whereas the second would produce numbers 0-9. That's because f(j++) is equivalent to j += 1; f(j);, whereas f(++i) is more like f(i); i += 1;.
May I advise that while your testing is fine on whatever platform you are using, the standard construct is i++
Always code the standard and isolate various platforms and make exceptions as needed !!!
i++ Simply means increment 'i' by one.
I can speculate ++i means to add 'i' to itself eg if 'i' was 2 then it would then increment to 2,4,8,16,32
But I have never seen ++i used in many places.

is there any significant performance difference between this 2 methods of for-loop usage?

Just wondering what is the difference in the following 2 methods?
var a = 0;
var b = 0;
var c = 0;
for(var i = 0; i < 6; i++ ){
a+=i;
b+=i;
c+=i;
}
and
var a = 0;
var b = 0;
var c = 0;
for(var i = 0; i < 6; i++ ){
a+=i;
}
for(var i = 0; i < 6; i++ ){
b+=i;
}
for(var i = 0; i < 6; i++ ){
c+=i;
}
*edited thanks locrizak for the correction
The second one is doing 3X the amount of iterations it needs to. In the second one there are 18 iterations through the loops while the first there is only 6 making the script run faster. (In these circumstances you will not notice a difference because you are not doing much in the loops but once you want to do more it will be a performance issue)
Ps. a+i isn;'t doing anything you probably want a+=i
When you are in doubt about JavaScript peformance, have an objective opinion:
http://jsperf.com/testing-snippets
Well, you are doing 3 times the work.
In the grand of scheme of things, 18 iterations of what your doing isn't going to have much impact, however comparitively it is much worse.
Without knowing any of the details of the javascript interpreter, assume that the second code block is marginally worse than the first, but definitely not worth refactoring if it makes the code harder to read. Think about it this way:
for(var i = 0; i < 6; i += 1) {
doSomeExpensiveThing(); // takes 500ms to process
doSomeExpensiveThing();
doSomeExpensiveThing();
}
And:
for(var i = 0; i < 6; i += 1) {
doSomeExpensiveThing(); // takes 500ms to process
}
for(var i = 0; i < 6; i += 1) {
doSomeExpensiveThing();
}
for(var i = 0; i < 6; i += 1) {
doSomeExpensiveThing();
}
The two are going to be effectively identical because the overhead of running the loop will disappear compared to the cost of doing the inner computation.
I disagree with locrizak. The second is definitely not doing 3 times the work since each loop has a third of the statements as the first example. The extra work on the second example is that it needs to run the loop iteration steps 2 times as often as the first example.
initalize i (only once)
increment i (every iteration)
check if i < 6; (every iteration)
Therefore, in any real world example where the loop has more statements and the loop overhead gets smaller and smaller, you're very unlikely to notice a difference. That means you shold use multiple loops if it makes the code more readable.
I created this more real-life example to prove my point that both loops are, for most intents and purposes, the same: http://jsperf.com/testing-snippets/3
The only difference is the number of assignments, additions and comparisons on the variable i - and unless you're programming for a 1970s embedded computer (which you're not, as this is JavaScript), the speed difference is effectively zero; do not waste time on trying to nanooptimize it (e.g. the speed of computers makes this a non-issue, and modern JS interpreters may compile it anyway, so the difference is lost altogether).
If you're doing anything meaningful inside those loops, that will be your bottleneck, not the looping itself.
The only significant difference is maintenance - so use whichever form is easier to understand for the next person down the line who will inherit this.
Paste it into the firebug console and time it. Making it work with large loops and you can see the differences easier.
console.time("group");
for(var x = 0; x<1000; x++){
var a = 0;
var b = 0;
var c = 0;
for(var i = 0; i < 6; i++ ){
a+i;
b+i;
c+i;
}
}
console.timeEnd("group");
console.time("sep");
for(var x = 0; x<1000; x++){
var a = 0;
var b = 0;
var c = 0;
for(var i = 0; i < 6; i++ ){
a+i;
}
for(var i = 0; i < 6; i++ ){
b+i;
}
for(var i = 0; i < 6; i++ ){
c+i;
}
}
console.timeEnd("sep");
I get
group: 8ms
sep: 13ms

Categories