-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

4
  • 1
    What's they point of if(arr[i])? Hint, hint Commented Nov 20, 2016 at 16:18
  • What is if(arr[i]) supposed to do? Commented Nov 20, 2016 at 16:19
  • check, if arr[i] exists Commented Nov 20, 2016 at 16:23
  • @Ludmila stackoverflow.com/questions/1961528/… Commented Nov 20, 2016 at 16:26

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);

Comments

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);

2 Comments

Always compare to null using abstract (!=) instead of script (!==) equality. (See 16204840)
I thouht i could because null in an Object. But i'm far for being an expert, so I keep your advice.
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.