Cant fully understand how to works array

Sorry, guys. But I cant understand why I constantly get a ReferenceError. Below a simple array code when you enter two digits in console.log shows numbers between them divided like % 2 .
But when I try to add capability of eliminate : null, ‘string’, and etc. it shows a ReferenceError by
arr.push(i);

for example

    for (let i = min; i <= max; i++){
    if (i % 4 == 0) {
      if (i === null) {
        alert('qwerty');
      }
    }
   }
      arr.push(i);
      return arr;
    };

This is original code. it works but without filter

let first = +prompt('Please enter first number:');
let second = +prompt('Please enter second number ');

function arrRange(min, max) {
  let arr = [];
  
  for (let i = min; i <= max; i++) 
    if (i % 2 == 0) 
   
  arr.push(i);
  return arr;
};

console.log(arrRange(first ,second ))

2 thoughts on “Cant fully understand how to works array”

  1. That is because you are pushing i to the arr in a wrong place. You just mixed the scopes of function.

    There you have a simple solution:

    for (let i = min; i <= max; i++){
        if (i % 4 == 0) {
          if (i === null) {
            alert('qwerty');
          }
            arr.push(i);
        }
        
       }
         
          return arr;
        };
    
    Reply
  2. In your example i is out of loop that is why you get Reference error.
    You cant fix it just by transfer your push method inside loop

       for (let i = min; i <= max; i++){
        if (i % 4 == 0) {
          if (i === null) {
            alert('qwerty');
          }
        }
        arr.push(i); 
       }
          // arr.push(i); out of loop and i here doesn't exist 
          return arr;
        };
    

    Reply

Leave a Comment