-1

I'm trying to iterate through the array of numbers and print all its elements

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function q(arr) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i]) {
      console.log(arr[i]);
    }
  }
}

q(arr);

The array contains 11 elements, but my code prints only 10 (except the 1'st element). But why? And how can i print my array completely?

Thank you

P.S.
  • 15,970
  • 14
  • 62
  • 86
Ludmila
  • 39
  • 7

5 Answers5

3

In the array element 0 is a falsy value so it won't get printed since there is an if statement which checks the elements is truthy.

There is no reason to use an if condition if you just want to iterate so remove the if condition to get it print.

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function q(arr) {
  for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
}

q(arr);

FYI : In case you want to avoid null values then use condition as arr[i] !== null instead.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

The problem is in your if statement. The arr[0] returns 0 which is a falsy value and thus the code inside the if statement will not be executed. Remove the if statement and it should work as i is always < than the length of the array

Ahmed
  • 23
  • 7
0

Just remove if condition . when if(arr[0]) it will not satisfied

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function q(arr) {
  for(var i=0; i<arr.length; i++) {
    
      console.log(arr[i]);
    
  }
}

q(arr);
Mahi
  • 1,707
  • 11
  • 22
0

just check if each element !== null

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function q(arr) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i] != null) {
      console.log(arr[i]);
    }
  }
}

q(arr);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
  • Always compare to `null` using abstract (`!=`) instead of script (`!==`) equality. (See [16204840](https://stackoverflow.com/questions/16204840/javascript-comparing-to-null-vs)) – naeramarth7 Nov 20 '16 at 16:26
  • I thouht i could because null in an Object. But i'm far for being an expert, so I keep your advice. – kevin ternet Nov 20 '16 at 16:33
-1

The first element of arr array (0) evaluates to false inside your if statement.

Here is the working snippet:

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function q(arr) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i] || arr[i] === 0) {
      console.log(arr[i]);
    }
  }
}

q(arr);

To get what you want, your if statement should look like this: arr[i] || arr[i] === 0. And i reccomend you to read about coercion to understand what's really is going on.

And you don't really need if statement here

P.S.
  • 15,970
  • 14
  • 62
  • 86