0

So i was working on a function which takes anything as argument and console logs it inside a box or a cell. This is what i came up with:

var horiz='━';
var vert='┃';
var ulcor='┏';
var urcor='┓';
var blcor='┗';
var brcor='┛';

//create a cell/box
var cell=(d='')=>{
    let h='';
    if(d==undefined||d==null){
        throw('cell needs an argument');
    }
    len=d.toString().length;
    for(i=0;i<3;i++){
        if(i==0){
            for(j=0;j<len;j++){
                h+=horiz;
            }
            if(i==0) console.log(ulcor+h+urcor);
        }
        if(i==1){
            console.log(`${vert}${d}${vert}`);
        }
        if(i==2){
           console.log(blcor+h+brcor);    
        }
    }
}

Now when i was testing this i did following

cell('index');
cell(1);

gave following output:

┏━━━━━┓
┃index┃
┗━━━━━┛
┏━┓
┃1┃
┗━┛

and did other testing as well and it worked pretty well until i did the following test:

for(i=0;i<5;i++){
   cell(i)
}

Above code should give me cells/boxes with 1,2,3,4 but instead this gave me an infinite loop and what i noticed is that its only printing cells with 4 (not 1,2 or 3) but infinite times.

And now here is the fun part. When I do following:

n=1;
while(n<10){
  cell(n);
  n+=1;
}

above code gives desired result and works fine. Weird!! just Couldn't figure out why its running infinite times when i used it in the for loop but while loop works good. If any sort of improvement required in the code then please do mention it:)

DarthCucumber
  • 101
  • 1
  • 8
  • 4
    Your re using the global variable `i` in the for loop version. – Keith Jun 06 '20 at 16:23
  • 1
    Variables in JS should always be defined with **let** or **const**. Especially in a for-loop `for (let i = 0; ...` – Ebuall Jun 06 '20 at 16:31
  • 1
    Run your code in strict mode and it should tell you about the coding problem you have. If you don't know about strict mode, [read](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) about it. Your code is running in "sloppy mode" and you're paying the price for that. – jfriend00 Jun 06 '20 at 16:33

1 Answers1

1

When you declare a variable without the var, let, or const keywords, that variable is an implicit global. In your cell function, you use for(i=0;i<3;i++) where i is declared without a keyword.

Your calling for loop for(i=0;i<5;i++){ cell(i) } also uses i without a keyword which makes i refer to the same global variable. So your call function is actually manipulating i from within the function which makes the for loop behave in the unintended manner. The while loop uses a different variable, n, which is why it doesn't have the same problem.

Try changing the for loop inside call to for(let i = 0; i < 3; i++) to limit the scope of i. And, in general, use let and const to declare ALL variables, even (and especially) the ones in for loops.

Elan Hamburger
  • 2,137
  • 10
  • 14