What is the difference between the two nested loops in javascript? -


function a() {     var n1 = 0,         n2 = 0;     (; n1 < 100; n1++) {         (; n2 < 100; n2++) {             console.log(2);         }         console.log(1);     } } a();  function b() {     (var n1 = 0; n1 < 100; n1++) {         (var n2 = 0; n2 < 100; n2++) {             console.log(2);         }         console.log(1);     } } b(); 

as can see.two simple nested loops,and looks have same output.but puzzles me function a() not output expected result,it loops outside , inside 100 times respectively.what's difference?

in b() function n2 variable created (see @jfriend00 comment) reset during every a loop iteration. set 0 , therefore b loop goes whole length (100 times).

in a variable n1 created once before inner loop, after first a iteration (and 100 b), n2 has value of 100. in second a interation n2 checked if it's less 100. it's not, inner loop ends before started.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

android - Go back to previous fragment -